性能优化之——.NET(C#)调用webService获取客户端IP地址所属区域(异步回调)(二)

8/3/2015来源:C#应用人气:3479

性能优化之——.NET(C#)调用webService获取客户端ip地址所属区域(异步回调)(二)

朋友们这次分享的是异步回调不是异步调用哦!

请注意喽!

功能描述接口地址方法名称以及参数说明,同上篇:.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 }

测试结果如下:

好了朋友们,得睡了,做个健康的程序员,晚安!^_^