在進行Winform程序開發須要進行大量的數據的讀寫操做的時候,每每會須要必定的時間,然在這個時間段裏面,界面ui得不到更新,致使在用戶看來界面處於假死的狀態,形成了很差的用戶體驗。因此在大量數據操做的應用上,須要使用多線程來處理這種狀況。在c#中使用多線程很方便只須要使用System.Threading.Thread的一個實例的Start方法就好了,可是如何實現多線程之間的交互就不是那麼簡單。本文實現了用子線程去處理數據,並實時更新主線程的ui狀態了。下面就開始一步步的去實現異步線程更新ui的demo程序吧。c#
應用背景 多線程
實現過程異步
一、首先創建一個winform項目,在主窗體上拖入一個button,一個progressbar,一個lable。以下圖所示。函數
public class DataWrite { public delegate void UpdateUI(int step);//聲明一個更新主線程的委託 public UpdateUI UpdateUIDelegate; public delegate void AccomplishTask();//聲明一個在完成任務時通知主線程的委託 public AccomplishTask TaskCallBack; public void Write(object lineCount) { StreamWriter writeIO = new StreamWriter("text.txt", false, Encoding.GetEncoding("gb2312")); string head = "編號,省,市"; writeIO.Write(head); for (int i = 0; i < (int)lineCount; i++) { writeIO.WriteLine(i.ToString() + ",湖南,衡陽"); //寫入一條數據,調用更新主線程ui狀態的委託 UpdateUIDelegate(1); } //任務完成時通知主線程做出相應的處理 TaskCallBack(); writeIO.Close(); } }
delegate void AsynUpdateUI(int step);
private void btnWrite_Click(object sender, EventArgs e) { int taskCount = 10000; //任務量爲10000 this.pgbWrite.Maximum = taskCount; this.pgbWrite.Value = 0; DataWrite dataWrite = new DataWrite();//實例化一個寫入數據的類 dataWrite.UpdateUIDelegate += UpdataUIStatus;//綁定更新任務狀態的委託 dataWrite.TaskCallBack += Accomplish;//綁定完成任務要調用的委託 Thread thread = new Thread(new ParameterizedThreadStart(dataWrite.Write)); thread.IsBackground = true; thread.Start(taskCount); } //更新UI private void UpdataUIStatus(int step) { if (InvokeRequired) { this.Invoke(new AsynUpdateUI(delegate(int s) { this.pgbWrite.Value += s; this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString(); }), step); } else { this.pgbWrite.Value += step; this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString(); } } //完成任務時須要調用 private void Accomplish() { //還能夠進行其餘的一些完任務完成以後的邏輯處理 MessageBox.Show("任務完成"); }