异步编程模型(APM)

原文 http://www.cnblogs.com/wang_yb/archive/2011/11/29/2267790.htmlhtml

 

APM是.NET中异步编程模型的缩写(Asynchronous Programing Model)编程

经过异步编程, 使得咱们的程序能够更加高效的利用系统资源.异步

 

1. APM例子异步编程

  .Net中的异步模型很是完善,只要看到Begin***者End***方法。基本都是相对***方法的异步调用方式。spa

  (注:***是方法的名称)线程

  因此在.Net中实现一个异步调用是很方便的,下面用个小例子来演示一个异步操做。code

  首先是同步的方式请求百度搜索10次。(百度分别搜索"1" , "2" , "3"..."10")orm

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 using System.Diagnostics;
 7 using System.Threading.Tasks;
 8 using System.Net;
 9 
10 namespace Thread2
11 {
12     class Program
13     {
14         static void Main(string[] args)
15         {
16             DateTime start = DateTime.Now;
17             string strReq = "http://www.baidu.com/s?wd={0}";
18             for (int i = 0; i < 10; i++)
19             {
20                 var req = WebRequest.Create(string.Format(strReq, i));
21                 var res = req.GetResponse();  //这是同步方法
22                 Console.WriteLine("检索 {0} 的结果已经返回!", i);
23                 res.Close();
24             }
25             Console.WriteLine("耗用时间:{0}毫秒", TimeSpan.FromTicks(DateTime.Now.Ticks - start.Ticks).TotalMilliseconds);
26             Console.ReadKey(true);
27         }
28     }
29 }               

  

  异步完成状况以下htm

  

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 using System.Diagnostics;
 7 using System.Threading.Tasks;
 8 using System.Net;
 9 
10 namespace Thread2
11 {
12     class Program
13     {
14         static DateTime start;
15         static void Main(string[] args)
16         {
17             start = DateTime.Now;
18             string strReq = "http://www.baidu.com/s?wd={0}";
19             for (int i = 0; i < 10; i++)
20             {
21                 var req = WebRequest.Create(string.Format(strReq, i));
22                 var res = req.BeginGetResponse(ProcessWebResponse,req);  //这是同步方法
23             }
24             Console.ReadKey(true);
25         }
26         private static void ProcessWebResponse(IAsyncResult result)
27         {
28             var req = (WebRequest)result.AsyncState;
29             string strReq = req.RequestUri.AbsoluteUri;
30             using (var res = req.EndGetResponse(result))
31             {
32                 Console.Write("检索 {0} 的结果已经返回!\t", strReq.Substring(strReq.Length - 1));
33                 Console.WriteLine("耗用时间:{0}毫秒", TimeSpan.FromTicks(DateTime.Now.Ticks - start.Ticks).TotalMilliseconds);
34             }
35         }
36     }
37 }               

 

  2.GUI 中的APMblog

  异步编程除了在服务端会大量应用,在有GUI的客户端也应用比较多(为了保证客户端的界面不会假死)。

  可是Winform或WPF程序中,改变界面元素状态只有经过UI线程,其余线程若是试图改变UI元素,就会抛出异常(System.InvalidOperationException)。

相关文章
相关标签/搜索