先看一个小例子:C#客户端打开一个控件,控件中加载了好多数据大约要用5秒中,如果我们直接打开控件,那么这个控件就要5秒中才能弹出来,当然这个时候用户已经把他Kill了。这个时候我们就需要先给用户把控件UI加载出来,给出来一个假象,然后数据在后台加载就OK了。具体看一下怎么做。
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 }
具体代码如下:
运行结果: