朋友們這次分享的是異步回調不是異步調用哦!
請注意喽!
功能描述,接口地址,方法名稱以及參數說明,同上篇:.NET(C#)調用webService獲取客戶端IP地址所屬區域(非異步)(一)(LZ比較懶,不想寫太多哦!(⊙0⊙))
實現代碼如下:
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 異步回調開始 =====");
15
16 GetCityIpHandler handler = new GetCityIpHandler(GetIp);
17
18 ////其核心在於IAsyncResult接口的實現
19 IAsyncResult res = handler.BeginInvoke(strIP, new AsyncCallback(GetIpSyn), string.Format("===== 主線程耗時{0}毫秒! =====", sw.ElapsedMilliseconds));
20
21 Console.WriteLine("===== 繼續執行其他的事情... =====");
22
23 Console.WriteLine("===== AsyncInvoke 異步回調完畢!=====");
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();//這裡我們進行漫長的調用
42 return Result = string.Format("IP歸屬地為{0},查詢耗時為{1}毫秒.", strArea_IP[1], sw.ElapsedMilliseconds);
43 }
44 /// <summary>
45 /// 異步回調方法
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); //打印調用GetIp返回的數據
53 object obj = result.AsyncState;
54 Console.WriteLine(obj);//打印返回結果:用戶定義的對象,它限定或包含關於異步操作的信息。
55 }
56 }
57 }
測試結果如下:

好了朋友們,得睡了,做個健康的程序員,晚安!^_^
補充一句,如果您覺得此文還算不錯的話可以收藏該文如果您覺得LZ的博客還不錯的話可以關注我或者與我聯系請多支持,謝謝!好文要頂 