異步編程模型(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)。

相關文章
相關標籤/搜索