using System; using System.Windows.Forms; /////////////////////////// using System.Diagnostics; using System.Net.Http; using System.Threading.Tasks; namespace simpleasync { /// <summary> /// framework4.5 異步demo /// </summary> public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// !事件修飾符 async /// </summary> private async void startbtn_Click(object sender, EventArgs e) { Task<string> getWebPageTask = GetWebPageAsync("http://www.cnblogs.com"); Debug.WriteLine("在 startButton_Click 任務執行前"); string webText = await getWebPageTask; Debug.WriteLine("返回字符數: " + webText.Length.ToString()); } private async Task<string> GetWebPageAsync(string url) { // 開始異步任務 Task<string> getStringTask = (new HttpClient()).GetStringAsync(url); // 在等待任務的時候 會作下面兩個事情 // 1. 當即執行返回到調用方法, 返回一個不一樣的任務給任務被建立的前面聲明的地方 // 在這個方法裏執行暫停. // 2. 當在前面聲明的任務建立完成後, 從GetStringAsync這個方法中產生等待語句, // 並在這個方法中繼續執行 Debug.WriteLine("在 GetWebPageAsync 等待以前"); string webText = await getStringTask; Debug.WriteLine("在 GetWebPageAsync 等待以後"); return webText; } private async Task<string> DelayAsync() { await Task.Delay(100); // 取消如下注釋 證實異常處理 //throw new OperationCanceledException("canceled"); //throw new Exception("Something happened."); return "Done"; } private async void asyncbtn_Click(object sender, EventArgs e) { Task<string> theTask = DelayAsync(); try { string result = await theTask; Debug.WriteLine("Result: " + result); } catch (Exception ex) { Debug.WriteLine("Exception Message: " + ex.Message); } Debug.WriteLine("Task IsCanceled: " + theTask.IsCanceled); Debug.WriteLine("Task IsFaulted: " + theTask.IsFaulted); if (theTask.Exception != null) { Debug.WriteLine("Task Exception Message: " + theTask.Exception.Message); Debug.WriteLine("Task Inner Exception Message: " + theTask.Exception.InnerException.Message); } } } }
二、程序運行結果:web
三、到底在異步的過程當中發生了什麼?app
這有個相似的程序:異步
原文連接:async
http://blogs.msdn.com/b/csharpfaq/archive/2012/06/26/understanding-a-simple-async-program.aspxurl
http://msdn.microsoft.com/en-us/library/vstudio/hh191443(v=vs.110).aspxspa