多进程处理之BackgroundWorker
说明:通过本例对BackgroundWorker的WorkerReportsProgress,WorkerSupportsCancdllation属性及Dowork,ProessChanged,RunWorkerCompleted事件做进一步的了解。
1 public partial class Form1 : Form 2 { 3 public Form1() 4 { 5 InitializeComponent(); 6 7 //获取或设置一个值,该值指示BW报告能否报告进度更新 8 backgroundWorker1.WorkerReportsProgress = true; 9 //获取或设置一个值,该值指示BW是否支持异步取消 10 backgroundWorker1.WorkerSupportsCancellation = true; 11 buttonStop.Enabled = false; 12 } 13 14 private void buttonStart_Click(object sender, EventArgs e) 15 { 16 richTextBox1.Text = "开始产生10000以内的随机数……\n\n"; 17 buttonStart.Enabled = false; 18 buttonStop.Enabled = true; 19 //在后台开始操作 20 backgroundWorker1.RunWorkerAsync(); 21 } 22 23 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 24 { 25 //不要直接使用组件实例名称(backgroundWorker1),因为有多 26 //个BackgroundWorker时,直接使用会产生耦合问题 27 //应该通过下面的转换使用它 28 BackgroundWorker worker = sender as BackgroundWorker; 29 //下面的内容相当于线程要处理的内容。注意:不要在此事件中和控件打交道 30 Random r = new Random(); 31 int numCount = 0; 32 while (worker.CancellationPending == false) 33 { 34 int num = r.Next(10000); 35 if (num % 5 == 0) 36 { 37 numCount++; 38 //引发BW.ProgressChanged()事件 39 worker.ReportProgress(0, num); 40 Thread.Sleep(1000); 41 } 42 } 43 //DoworkEventArgs.Result 获取或设置表示异步操作结果的值 44 e.Result = numCount; 45 } 46 47 48 private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) 49 { 50 //object ProgressChangedEventArgs.UserState 获取唯一的用户状态 51 int num = (int)e.UserState; 52 richTextBox1.Text += num + ","; 53 } 54 55 private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 56 { 57 if (e.Error == null) 58 { 59 richTextBox1.Text += "\n\n操作停止,共产生"+e.Result+"个能被5整除的随机数"; 60 } 61 else 62 { 63 richTextBox1.Text += "\n操作过程中产生错误:" + e.Error; 64 } 65 66 } 67 68 private void buttonStop_Click(object sender, EventArgs e) 69 { 70 //请求取消挂起后的操作 71 backgroundWorker1.CancelAsync(); 72 buttonStop.Enabled = false; 73 buttonStart.Enabled = true; 74 } 75 }