新進階的程序員可能對async、await用得比較多,卻對之前的異步了解甚少。本人就是此類,因此打算回顧學習下異步的進化史。
本文主要是回顧async異步模式之前的異步,下篇文章再來重點分析async異步模式。
APM 異步編程模型,Asynchronous PRogramming Model
早在C#1的時候就有了APM。雖然不是很熟悉,但是多少還是見過的。就是那些類是BeginXXX和EndXXX的方法,且BeginXXX返回值是IAsyncResult接口。
在正式寫APM示例之前我們先給出一段同步代碼:

//1、同步方法private void button1_Click(object sender, EventArgs e){ Debug.WriteLine("【Debug】線程ID:" + Thread.CurrentThread.ManagedThreadId); var request = WebRequest.Create("https://github.com/");//為了更好的演示效果,我們使用網速比較慢的外網 request.GetResponse();//發送請求 Debug.WriteLine("【Debug】線程ID:" + Thread.CurrentThread.ManagedThreadId); label1.Text = "執行完畢!";}
【說明】為了更好的演示異步效果,這里我們使用winform程序來做示例。(因為winform始終都需要UI線程渲染界面,如果被UI線程占用則會出現“假死”狀態)
【效果圖】

看圖得知:
我們在執行方法的時候頁面出現了“假死”,拖不動了。我們看到打印結果,方法調用前和調用后線程ID都是9(也就是同一個線程)下面我們再來演示對應的異步方法:(BeginGetResponse、EndGetResponse所謂的APM異步模型)

private void button2_Click(object sender, EventArgs e){ //1、APM 異步編程模型,Asynchronous Programming Model //C#1[基于IAsyncResult接口實現BeginXXX和EndXXX的方法] Debug.WriteLine("【Debug】主線程ID:" + Thread.CurrentThread.ManagedThreadId); var request = WebRequest.Create("https://github.com/"); request.BeginGetResponse(new AsyncCallback(t =>//執行完成后的回調 { var response = request.EndGetResponse(t); var stream = response.GetResponseStream();//獲取返回數據流 using (StreamReader reader = new StreamReader(stream)) { StringBuilder sb = new StringBuilder(); while (!reader.EndOfStream) { var content = reader.ReadLine(); sb.Append(content); } Debug.WriteLine("【Debug】" + sb.ToString().Trim().Substring(0, 100) + "...");//只取返回內容的前100個字符 Debug.WriteLine("【Debug】異步線程ID:" + Thread.CurrentThread.ManagedThreadId); label1.Invoke((Action)(() => { label1.Text = "執行完畢!"; }));//這里跨線程訪問UI需要做處理 } }), null); Debug.WriteLine("【Debug】主線程ID:" + Thread.CurrentThread.ManagedThreadId); }
【效果圖】

看圖得知:
啟用異步方法并沒有是UI界面卡死異步方法啟動了另外一個ID為12的線程上面代碼執行順序:

前面我們說過,APM的BebinXXX必須返回IAsyncResult接口。那么接下來我們分析IAsyncResult接口:
首先我們看:

確實返回的是IAsyncResult接口。那IAsyncResult到底長的什么樣子?:

并沒有想象中的那么復雜嘛。我們是否可以嘗試這實現這個接口,然后顯示自己的異步方法呢?
首先定一個類MyWebRequest,然后繼承IAsyncResult:(下面是基本的偽代碼實現)

public class MyWebRequest : IAsyncResult{ public object AsyncState { get { throw new NotImplementedException(); } } public WaitHandle AsyncWaitHandle { get { throw new NotImplementedException(); } } public bool CompletedSynchronously { get { throw new NotImplementedException(); } } public bool IsCompleted { get { throw new NotImplementedException(); } }}
這樣肯定是不能用的,起碼也得有個存回調函數的屬性吧,下面我們稍微改造下:

然后我們可以自定義APM異步模型了:(成對的Begin、End)

public IAsyncResult MyBeginXX(AsyncCallback callback){ var asyncResult = new MyWebRequest(callback, null); var request = WebRequest.Create("https://github.com/"); new Thread(() => //重新啟用一個線程 { using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream())) { var str = sr.ReadToEnd(); asyncResult.SetComplete(str);//設置異步結果 } }).Start(); return asyncResult;//返回一個IAsyncResult}public string MyEndXX(IAsyncResult asyncResult){ MyWebRequest result = asyncResult as MyWebRequest; return result.Result;}
調用如下:

private void button4_Click(object sender, EventArgs e) { Debug.WriteLine("【Debug】主線程ID:" + Thread.CurrentThread.ManagedThreadId); MyBeginXX(new AsyncCallback(t => { var result = MyEndXX(t); Debug.WriteLine("【Debug】" + result.Trim().Substring(0, 100) + "..."); Debug.WriteLine("【Debug】異步線程ID:" + Thread.CurrentThread.ManagedThreadId); })); Debug.WriteLine("【Debug】主線程ID:" + Thread.CurrentThread.ManagedThreadId); }
效果圖:

我們看到自己實現的效果基本上和系統提供的差不多。
啟用異步方法并沒有是UI界面卡死異步方法啟動了另外一個ID為11的線程【總結】
個人覺得APM異步模式就是啟用另外一個線程執行耗時任務,然后通過回調函數執行后續操作。
APM還可以通過其他方式獲取值,如:
while (!asyncResult.IsCompleted)//循環,直到異步執行完成 (輪詢方式){ Thread.Sleep(100);}var stream2 = request.EndGetResponse(asyncResult).GetResponseStream();或
asyncResult.AsyncWaitHandle.WaitOne();//阻止線程,直到異步完成 (阻塞等待)var stream2 = request.EndGetResponse(asyncResult).GetResponseStream();
補充:如果是普通方法,我們也可以通過委托異步:(BeginInvoke、EndInvoke)

public void MyAction() { var func = new Func<string, string>(t => { Thread.Sleep(2000); return "name:" + t + DateTime.Now.ToString(); }); var asyncResult = func.BeginInvoke("張三", t => { string str = func.EndInvoke(t); Debug.WriteLine(str); }, null); }
EAP
EAP 基于事件的異步模式,Event-based Asynchronous Pattern
此模式在C#2的時候隨之而來。
先來看個EAP的例子:

private void button3_Click(object sender, EventArgs e) { Debug.WriteLine("【Debug】主線程ID:" + Thread.CurrentThread.ManagedThreadId); BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler((s1, s2) => { Thread.Sleep(2000); Debug.WriteLine("【Debug】異步線程ID:" + Thread.CurrentThread.ManagedThreadId); });//注冊事件來實現異步 worker.RunWorkerAsync(this); Debug.WriteLine("【Debug】主線程ID:" + Thread.CurrentThread.ManagedThreadId); }
【效果圖】(同樣不會阻塞UI界面)

【特征】
通過事件的方式注冊回調函數通過 XXXAsync方法來執行異步調用例子很簡單,但是和APM模式相比,是不是沒有那么清晰透明。為什么可以這樣實現?事件的注冊是在干嘛?為什么執行RunWorkerAsync會觸發注冊的函數?
感覺自己又想多了…
我們試著反編譯看看源碼:

只想說,這么玩,有意思嗎?
TAP
TAP 基于任務的異步模式,Task-based Asynchronous Pattern
到目前為止,我們覺得上面的APM、EAP異步模式好用嗎?好像沒有發現什么問題。再仔細想想…如果我們有多個異步方法需要按先后順序執行,并且需要(在主進程)得到所有返回值。
首先定義三個委托:

public Func<string, string> func1(){ return new Func<string, string>(t => { Thread.Sleep(2000); return "name:" + t; });}public Func<string, string> func2(){ return new Func<string, string>(t => { Thread.Sleep(2000); return "age:" + t; });}public Func<string, string> func3(){ return new Func<string, string>(t => { Thread.Sleep(2000); return "sex:" + t; });}
然后按照一定順序執行:

public void MyAction(){ string str1 = string.Empty, str2 = string.Empty, str3 = string.Empty; IAsyncResult asyncResult1 = null, asyncResult2 = null, asyncResult3 = null; asyncResult1 = func1().BeginInvoke("張三", t => { str1 = func1().EndInvoke(t); Debug.WriteLine("【Debug】異步線程ID:" + Thread.CurrentThread.ManagedThreadId); asyncResult2 = func2().BeginInvoke("26", a => { str2 = func2().EndInvoke(a); Debug.WriteLine("【Debug】異步線程ID:" + Thread.CurrentThread.ManagedThreadId); asyncResult3 = func3().BeginInvoke("男", s => { str3 = func3().EndInvoke(s); Debug.WriteLine("【Debug】異步線程ID:" + Thread.CurrentThread.ManagedThreadId); }, null); }, null); }, null); asyncResult1.AsyncWaitHandle.WaitOne(); asyncResult2.AsyncWaitHandle.WaitOne(); asyncResult3.AsyncWaitHandle.WaitOne(); Debug.WriteLine(str1 + str2 + str3);} 
除了難看、難讀一點好像也沒什么 。不過真的是這樣嗎?

asyncResult2是null?由此可見在完成第一個異步操作之前沒有對asyncResult2進行賦值,asyncResult2執行異步等待的時候報異常。那么如此我們就無法控制三個異步函數,按照一定順序執行完成后再拿到返回值。(理論上還是有其他辦法的,只是會然代碼更加復雜)
是的,現在該我們的TAP登場了。

只需要調用Task類的靜態方法Run,即可輕輕松松使用異步。
獲取返回值:

var task1 = Task<string>.Run(() =>{ Thread.Sleep(1500); Console.WriteLine("【Debug】task1 線程ID:" + Thread.CurrentThread.ManagedThreadId); return "張三";});//其他邏輯 task1.Wait();var value = task1.Result;//獲取返回值Console.WriteLine("【Debug】主 線程ID:" + Thread.CurrentThread.ManagedThreadId);
現在我們處理上面多個異步按序執行:

Console.WriteLine("【Debug】主 線程ID:" + Thread.CurrentThread.ManagedThreadId);string str1 = string.Empty, str2 = string.Empty, str3 = string.Empty;var task1 = Task.Run(() =>{ Thread.Sleep(500); str1 = "姓名:張三,"; Console.WriteLine("【Debug】task1 線程ID:" + Thread.CurrentThread.ManagedThreadId);}).ContinueWith(t =>{ Thread.Sleep(500); str2 = "年齡:25,"; Console.WriteLine("【Debug】task2 線程ID:" + Thread.CurrentThread.ManagedThreadId);}).ContinueWith(t =>{ Thread.Sleep(500); str3 = "愛好:妹子"; Console.WriteLine("【Debug】task3 線程ID:" + Thread.CurrentThread.ManagedThreadId);});Thread.Sleep(2500);//其他邏輯代碼task1.Wait();Debug.WriteLine(str1 + str2 + str3);Console.WriteLine("【Debug】主 線程ID:" + Thread.CurrentThread.ManagedThreadId);
[效果圖]

我們看到,結果都得到了,且是異步按序執行的。且代碼的邏輯思路非常清晰。如果你感受還不是很大,那么你現象如果是100個異步方法需要異步按序執行呢?用APM的異步回調,那至少也得異步回調嵌套100次。那代碼的復雜度可想而知。
延伸思考
WaitOne完成等待的原理
異步為什么會提升性能
線程的使用數量和CPU的使用率有必然的聯系嗎
問題1:WaitOne完成等待的原理
在此之前,我們先來簡單的了解下多線程信號控制AutoResetEvent類。
var _asyncWaitHandle = new AutoResetEvent(false);_asyncWaitHandle.WaitOne();此代碼會在 WaitOne 的地方會一直等待下去。除非有另外一個線程執行 AutoResetEvent 的set方法。
var _asyncWaitHandle = new AutoResetEvent(false);_asyncWaitHandle.Set();_asyncWaitHandle.WaitOne();如此,到了 WaitOne 就可以直接執行下去。沒有有任何等待。
現在我們對APM 異步編程模型中的 WaitOne 等待是不是知道了點什么呢。我們回頭來實現之前自定義異步方法的異步等待。

public class MyWebRequest : IAsyncResult{ //異步回調函數(委托) private AsyncCallback _asyncCallback; private AutoResetEvent _asyncWaitHandle; public MyWebRequest(AsyncCallback asyncCallback, object state) { _asyncCallback = asyncCallback; _asyncWaitHandle = new AutoResetEvent(false); } //設置結果 public void SetComplete(string result) { Result = result; IsCompleted = true; _asyncWaitHandle.Set(); if (_asyncCallback != null) { _asyncCallback(this); } } //異步請求返回值 public string Result { get; set; } //獲取用戶定義的對象,它限定或包含關于異步操作的信息。 public object AsyncState { get { throw new NotImplementedException(); } } // 獲取用于等待異步操作完成的 System.Threading.WaitHandle。 public WaitHandle AsyncWaitHandle { //get { throw new NotImplementedException(); } get { return _asyncWaitHandle; } } //獲取一個值,該值指示異步操作是否同步完成。 public bool CompletedSynchronously { get { throw new NotImplementedException(); } } //獲取一個值,該值指示異步操作是否已完成。 public bool IsCompleted { get; private set; }}
紅色代碼就是新增的異步等待。
【執行步驟】

問題2:異步為什么會提升性能
比如同步代碼:
Thread.Sleep(10000);//假設這是個訪問數據庫的方法Thread.Sleep(10000);//假設這是個訪問FQ網站的方法這個代碼需要20秒。
如果是異步:

var task = Task.Run(() =>{ Thread.Sleep(10000);//假設這是個訪問數據庫的方法});Thread.Sleep(10000);//假設這是個訪問FQ網站的方法task.Wait();
如此就只要10秒了。這樣就節約了10秒。
如果是:
var task = Task.Run(() =>{ Thread.Sleep(10000);//假設這是個訪問數據庫的方法}); task.Wait();異步執行中間沒有耗時的代碼那么這樣的異步將是沒有意思的。
或者:

var task = Task.Run(() =>{ Thread.Sleep(10000);//假設這是個訪問數據庫的方法}); task.Wait();Thread.Sleep(10000);//假設這是個訪問FQ網站的方法
把耗時任務放在異步等待后,那這樣的代碼也是不會有性能提升的。
還有一種情況:
如果是單核CPU進行高密集運算操作,那么異步也是沒有意義的。(因為運算是非常耗CPU,而網絡請求等待不耗CPU)
問題3:線程的使用數量和CPU的使用率有必然的聯系嗎
答案是否。
還是拿單核做假設。
情況1:

long num = 0;while (true){ num += new Random().Next(-100,100); //Thread.Sleep(100);}
單核下,我們只啟動一個線程,就可以讓你CPU爆滿。


啟動八次,八進程CPU基本爆滿。
情況2:


一千多個線程,而CPU的使用率竟然是0。由此,我們得到了之前的結論,線程的使用數量和CPU的使用率沒有必然的聯系。
雖然如此,但是也不能毫無節制的開啟線程。因為:
開啟一個新的線程的過程是比較耗資源的。(可是使用線程池,來降低開啟新線程所消耗的資源)多線程的切換也是需要時間的。每個線程占用了一定的內存保存線程上下文信息。
demo:http://pan.baidu.com/s/1slOxgnF
新聞熱點
疑難解答