朋友們這次分享的是異步回調(diào)不是異步調(diào)用哦!
請注意嘍!
功能描述,接口地址,方法名稱以及參數(shù)說明,同上篇:.NET(C#)調(diào)用webService獲取客戶端IP地址所屬區(qū)域(非異步)(一)(LZ比較懶,不想寫太多哦!(⊙0⊙))
實現(xiàn)代碼如下:
1 namespace main 2 { 3 class PRogram 4 { 5 public static string Result = string.Empty; 6 7 static void Main(string[] args) 8 { 9 10 Stopwatch sw = Stopwatch.StartNew();11 12 string strIP = "111.13.55.3";//請求的IP地址13 14 Console.WriteLine("===== AsyncInvoke 異步回調(diào)開始 =====");15 16 GetCityIpHandler handler = new GetCityIpHandler(GetIp);17 18 ////其核心在于IAsyncResult接口的實現(xiàn)19 IAsyncResult res = handler.BeginInvoke(strIP, new AsyncCallback(GetIpSyn), string.Format("===== 主線程耗時{0}毫秒! =====", sw.ElapsedMilliseconds));20 21 Console.WriteLine("===== 繼續(xù)執(zhí)行其他的事情... =====");22 23 Console.WriteLine("===== AsyncInvoke 異步回調(diào)完畢!=====");24 25 sw.Stop();26 27 Console.ReadLine();28 29 }30 public delegate string GetCityIpHandler(string strIp);31 /// <summary>32 /// 同步方法33 /// </summary>34 /// <param name="strIP"></param>35 /// <returns></returns>36 public static string GetIp(string strIp)37 {38 IpAddressSearchWebServiceSoapClient ws = new IpAddressSearchWebServiceSoapClient();39 Stopwatch sw = Stopwatch.StartNew();40 string[] strArea_IP = ws.getCountryCityByIp(strIp);41 sw.Stop();//這里我們進行漫長的調(diào)用42 return Result = string.Format("IP歸屬地為{0},查詢耗時為{1}毫秒.", strArea_IP[1], sw.ElapsedMilliseconds);43 }44 /// <summary>45 /// 異步回調(diào)方法46 /// </summary>47 /// <param name="result"></param>48 static void GetIpSyn(IAsyncResult result)49 {50 GetCityIpHandler hl = (GetCityIpHandler)((AsyncResult)result).AsyncDelegate;//AsyncResult 繼承自IAsyncResult接口51 Result = hl.EndInvoke(result);52 Console.WriteLine(Result); //打印調(diào)用GetIp返回的數(shù)據(jù)53 object obj = result.AsyncState;54 Console.WriteLine(obj);//打印返回結(jié)果:用戶定義的對象,它限定或包含關于異步操作的信息。55 }56 }57 }
測試結(jié)果如下:
好了朋友們,得睡了,做個健康的程序員,晚安!^_^
新聞熱點
疑難解答