標籤:
朋友們這次分享的是非同步回調不是非同步呼叫哦!
請注意嘍!
功能描述,介面地址,方法名稱以及參數說明,同上篇:.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的部落格還不錯的話可以關注我或者與我聯絡請多支援,謝謝!好文要頂
效能最佳化之——.NET(C#)調用webService擷取用戶端IP地址所屬地區(非同步回調)(二)