金科玉律:不要在UI線程上執行耗時的操做;不要在除了UI線程以外的其餘線程上訪問UI控件!異步
NET1.1的BeginInvoke異步調用,須要準備3個方法:功能方法GetWebsiteLength,結果方法DownloadComplete,呼叫方法BeginInvoke!async
但很不幸,在UI線程以外訪問UI線程控件!調用失敗。線程同步必須在線程所屬進程的公共區域保留同步區,以此實現線程間的通信。this
2、C#2.0引入了BackgroundWorker,從而極大的簡化了線程間通信。spa
3、C#4.0引入的async和await關鍵字,使得一切變得如此簡單!線程
async和await關鍵字3d
using System; using System.Windows.Forms; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AsyncDemo { class MyForm:Form { Label lblInfo; Button btnCaculate; public MyForm() { lblInfo = new Label { Location = new System.Drawing.Point(10, 20), Text = "Length" }; btnCaculate = new Button { Location = new System.Drawing.Point(10, 50), Text = "GetLength" }; btnCaculate.Click += DisplayWebsiteLength; AutoSize = true; this.Controls.Add(lblInfo); this.Controls.Add(btnCaculate); } async void DisplayWebsiteLength(object sender,EventArgs e) { lblInfo.Text = "Fetching..."; using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { //string text = await client.GetStringAsync("http://flaaash.cnblogs.com"); //lblInfo.Text = text.Length.ToString(); Task<string> task = client.GetStringAsync("http://www.sina.com"); string contents = await task; lblInfo.Text = contents.Length.ToString(); } } static void Main(string[] args) { Application.Run(new MyForm()); } } }
BackgroundWorkercode
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AsyncDemo { class BackWorker : Form { Label lblInfo; Button btnCaculate; System.ComponentModel.BackgroundWorker worker; BackWorker() { lblInfo = new Label { Location = new System.Drawing.Point(10, 20), Text = "Length" }; btnCaculate = new Button { Location = new System.Drawing.Point(10, 50), Text = "GetLength" }; btnCaculate.Click += (o, e) => { worker.RunWorkerAsync(); }; this.Controls.Add(lblInfo); this.Controls.Add(btnCaculate); worker = new System.ComponentModel.BackgroundWorker(); worker.DoWork += (o, e) => { System.Net.WebClient client = new System.Net.WebClient(); string contents = client.DownloadString("http://www.sina.com"); e.Result = contents.Length; }; worker.RunWorkerCompleted += (o, e) => lblInfo.Text = e.Result.ToString(); } public static void MainTest(string[] args) { Application.Run(new BackWorker()); } } }