在.Net 4.5中,通過async和await兩個關鍵字,引入了一種新的基於任務的非同步編程模型(TAP)。在這種方式下,可以通過類似同步方式編寫非同步代碼,極大簡化了非同步編程模型。如下式一個簡單的實例: 而之前的方式是這樣的: 也許前面這個例子不足以體現async和await帶來的優越性,下麵這個例 ...
在.Net 4.5中,通過async和await兩個關鍵字,引入了一種新的基於任務的非同步編程模型(TAP)。在這種方式下,可以通過類似同步方式編寫非同步代碼,極大簡化了非同步編程模型。如下式一個簡單的實例:
static async void DownloadStringAsync2(Uri uri) { var webClient = new WebClient(); var result = await webClient.DownloadStringTaskAsync(uri); Console.WriteLine(result); }
而之前的方式是這樣的:
static void DownloadStringAsync(Uri uri) { var webClient = new WebClient(); webClient.DownloadStringCompleted += (s, e) => { Console.WriteLine(e.Result); }; webClient.DownloadStringAsync(uri); }
也許前面這個例子不足以體現async和await帶來的優越性,下麵這個例子就明顯多了:
public void CopyToAsyncTheHardWay(Stream source, Stream destination) { byte[] buffer = new byte[0x1000]; Action<IAsyncResult> readWriteLoop = null; readWriteLoop = iar => { for (bool isRead = (iar == null); ; isRead = !isRead) { switch (isRead) { case true: iar = source.BeginRead(buffer, 0, buffer.Length, readResult => { if (readResult.CompletedSynchronously) return; readWriteLoop(readResult); }, null); if (!iar.CompletedSynchronously) return; break; case false: int numRead = source.EndRead(iar); if (numRead == 0) { return; } iar = destination.BeginWrite(buffer, 0, numRead, writeResult => { if (writeResult.CompletedSynchronously) return; destination.EndWrite(writeResult); readWriteLoop(null); }, null); if (!iar.CompletedSynchronously) return; destination.EndWrite(iar); break; } } }; readWriteLoop(null); } public async Task CopyToAsync(Stream source, Stream destination) { byte[] buffer = new byte[0x1000]; int numRead; while ((numRead = await source.ReadAsync(buffer, 0, buffer.Length)) != 0) { await destination.WriteAsync(buffer, 0, numRead); } }
可參看微軟的官方網站:Visual Studio Asynchronous Programming,其官方文檔Task-Based Asynchronous Pattern Overview介紹的非常詳細, VisualStudio中自帶的CSharp Language Specification中也有一些說明。
源自:http://blog.csdn.net/wulex/article/details/73499500