先看一個小例子:C#客戶端打開一個控件,控件中加載了好多數據大約要用5秒中,若是咱們直接打開控件,那麼這個控件就要5秒中才能彈出來,固然這個時候用戶已經把他Kill了。這個時候咱們就須要先給用戶把控件UI加載出來,給出來一個假象,而後數據在後臺加載就OK了。具體看一下怎麼作。async
1 public Form1() 2 { 3 InitializeComponent(); 4 5 //若是要設置進度條和取消事件,則必須先設定他們的屬性能夠執行 6 backgroundWorker1.WorkerReportsProgress=true; 7 backgroundWorker1.WorkerSupportsCancellation=true; 8 9 //註冊要執行的耗時事件 10 backgroundWorker1.DoWork += backgroundWorker1_DoWork; 11 //註冊進度條事件 12 backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged; 13 //註冊執行完backgroundworker事件 14 backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted; 16 } 17 18 /// <summary> 19 /// 點擊開始 20 /// </summary> 21 /// <param name="sender"></param> 22 /// <param name="e"></param> 23 private void startAsyncButton_Click(object sender, EventArgs e) 24 { 25 //這裏作判斷就是判斷backgroundWorker是否在執行,若是沒有在執行就開始工做,執行Dowork中的事件 26 if (!backgroundWorker1.IsBusy) 27 { 28 backgroundWorker1.RunWorkerAsync(); 29 } 30 } 31 32 /// <summary> 33 /// 開始執行耗時事件 34 /// </summary> 35 /// <param name="sender"></param> 36 /// <param name="e"></param> 37 private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) 38 { 39 BackgroundWorker worker = sender as BackgroundWorker; 40 for (int i = 1; i <= 10; i++) 41 { 42 if (worker.CancellationPending) 43 { 44 e.Cancel = true; 45 break; 46 } 47 else 48 { 49 Thread.Sleep(500); 50 //更改進度條值,觸發進度條事件,這裏不能實現UI代碼,要在進度條改變事件裏實現 51 worker.ReportProgress(i * 10); 52 } 53 } 54 } 55 56 /// <summary> 57 /// 點擊取消執行事件 58 /// </summary> 59 /// <param name="sender"></param> 60 /// <param name="e"></param> 61 private void cancelAsyncButton_Click(object sender, EventArgs e) 62 { 63 if (backgroundWorker1.WorkerSupportsCancellation == true) 64 { 65 // Cancel the asynchronous operation. 66 backgroundWorker1.CancelAsync(); 67 } 68 } 69 70 71 /// <summary> 72 /// 進度條改變事件 73 /// </summary> 74 /// <param name="sender"></param> 75 /// <param name="e"></param> 76 private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e) 77 { 78 radLabel1.Text = (e.ProgressPercentage.ToString() + "%"); 79 } 80 81 /// <summary> 82 /// backgroundWorker1執行完事件 83 /// </summary> 84 /// <param name="sender"></param> 85 /// <param name="e"></param> 86 private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) 87 { 88 } 89 }
具體代碼以下:spa
運行結果:
code