C# BackGroundWorker实现窗体不卡死 进度条功能
网上的例子少了好多属性的配置,改好了一个能直接用的:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 10 namespace XXXX 11 { 12 public partial class BackGroundWorker : Form 13 { 14 public BackGroundWorker() 15 { 16 InitializeComponent(); 17 backgroundWorker1.WorkerReportsProgress = true; 18 backgroundWorker1.WorkerSupportsCancellation = true; 19 backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged); 20 backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted); 21 backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork); 22 progressBar1.Maximum = 10000; 23 } 24 25 //这里就是通过响应消息,来处理界面的显示工作 26 private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) 27 { 28 this.progressBar1.Value = e.ProgressPercentage; 29 this.label1.Text = e.UserState.ToString(); 30 this.label1.Update(); 31 } 32 33 //这里是后台工作完成后的消息处理,可以在这里进行后续的处理工作。 34 private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 35 { 36 MessageBox.Show("运算终于完成了"); 37 } 38 39 //这里,就是后台进程开始工作时,调用工作函数的地方。你可以把你现有的处理函数写在这儿。 40 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 41 { 42 work(this.backgroundWorker1); 43 } 44 45 //真正的处理工作 46 private bool work(BackgroundWorker bk) 47 { 48 int tatle = 10001; 49 50 for (int i = 0; i < tatle; i++) 51 { 52 if (bk.CancellationPending) //这里判断一下是否用户要求取消后台进行,并可以尽早退出。 53 { 54 bk.ReportProgress(i, String.Format("当前值是 {0},操作被用户申请中断", i)); 55 return false; 56 } 57 58 //处理的过程中,通过这个函数,向主线程报告处理进度,最好是折算成百分比,与外边的进度条的最大值必须要对应。这里,我没有折算,而是把界面线程的进度条最大值调整为与这里的总数一致。 59 bk.ReportProgress(i, String.Format("当前值是 {0} ", i)); 60 } 61 return true; 62 } 63 64 private void button2_Click(object sender, EventArgs e) 65 { 66 //用户要求取消时,就这样处理一下。有时不太灵喔。 67 this.backgroundWorker1.CancelAsync(); 68 } 69 70 private void button1_Click(object sender, EventArgs e) 71 { 72 if (this.backgroundWorker1.IsBusy) 73 return; 74 this.backgroundWorker1.RunWorkerAsync(); 75 } 76 77 private void button3_Click(object sender, EventArgs e) 78 { 79 this.Close(); 80 } 81 } 82 }
窗体摆几个控件就可以了