日期:2018年11月28日
环境:Windows 10,VS2015
前言
.NET 类库中提供了一个快捷使用多线程的帮助类BackgroundWorker,能够快速创建一个新的线程,并能报告进度,暂停,以及在线程完成后处理别的任务。
创建简单UI
Demo code
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.Threading; 9 using System.Threading.Tasks; 10 using System.Windows.Forms; 11 12 namespace BackgroundWorkerTest 13 { 14 public partial class Form1 : Form 15 { 16 private BackgroundWorker bkgdWorker; 17 public Form1() 18 { 19 InitializeComponent(); 20 } 21 22 private void Form1_Load(object sender, EventArgs e) 23 { 24 bkgdWorker = new BackgroundWorker(); 25 bkgdWorker.WorkerReportsProgress = true;//允许报告进度 26 bkgdWorker.WorkerSupportsCancellation = true;//允许取消线程 27 bkgdWorker.DoWork += new DoWorkEventHandler(bkgdWorker_DoWork);//添加主要工作 28 bkgdWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bkgdWorker_RunWorkerCompleted);//添加线程完成的处理 29 bkgdWorker.ProgressChanged += new ProgressChangedEventHandler(bkgdWorker_ProgressChanged);//添加进度变化处理 30 } 31 32 //主要工作逻辑(不可处理UI相关) 33 private void bkgdWorker_DoWork(Object sender, DoWorkEventArgs e) 34 { 35 BackgroundWorker bw = (BackgroundWorker)sender; 36 int n = 0; 37 long sum = 0; 38 39 if (e.Argument != null) 40 { 41 n = (int)e.Argument; 42 } 43 44 for (int i=0;i<= n; i++) 45 { 46 if (bw.CancellationPending) 47 { 48 e.Cancel = true;//此处设置Cancel=true后,就可以在RunWorkerCompleted中判断e.Cancelled是否为true 49 break; 50 } 51 sum += i; 52 Thread.Sleep(10);//避免太快,让线程暂停一会再报告进度 53 //bw.ReportProgress(i/10);//报告进度//调用ReportProgress()方法报告进度,同时触发ProgressChanged事件 54 bw.ReportProgress(i / 10, "当前i的值为"+ Convert.ToString(i));//报告进度和userState 55 } 56 e.Result = sum; 57 } 58 59 //进度变化处理 60 private void bkgdWorker_ProgressChanged(Object sender, ProgressChangedEventArgs e) 61 { 62 pbr_Test.Value = e.ProgressPercentage; 63 lb_Message.Text = e.UserState.ToString(); 64 } 65 66 //线程完成处理 67 private void bkgdWorker_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e) 68 { 69 if (!(e.Error == null)) 70 { 71 MessageBox.Show("Fail:"+e.Error.Message); 72 } 73 else if(e.Cancelled) 74 { 75 MessageBox.Show("Failed: thread Cancelled by operator"); 76 } 77 else 78 { 79 lb_Message.Text = "计算结果为:" + e.Result.ToString(); 80 MessageBox.Show("thread complete"); 81 } 82 } 83 84 private void btn_Start_Click(object sender, EventArgs e) 85 { 86 if (bkgdWorker.IsBusy) 87 MessageBox.Show("The thead running now."); 88 else 89 bkgdWorker.RunWorkerAsync(1000);//调用该方法才会启动线程 90 } 91 92 private void btn_Cancal_Click(object sender, EventArgs e) 93 { 94 if (bkgdWorker.IsBusy) 95 { 96 bkgdWorker.CancelAsync();//取消线程 97 } 98 else 99 { 100 MessageBox.Show("There is no thead running now."); 101 } 102 } 103 } 104 }