private void btnRunBackgroundWorker_Click(object sender, EventArgs e) { Console.WriteLine($"主线程:{Thread.CurrentThread.ManagedThreadId}"); InitBackgroundTask(); } BackgroundWorker worker = null; private void InitBackgroundTask() { worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler ( (object sender, DoWorkEventArgs e) => { Console.WriteLine($"--------------- 执行复杂任务, 线程: {Thread.CurrentThread.ManagedThreadId}"); for (int i = 0; i < 100; i++) { if (worker.CancellationPending) { e.Cancel = true; return; } worker.ReportProgress(i + 1); e.Result = 100 + i; Thread.Sleep(30); } Console.WriteLine("--------------- 执行复杂任务结束."); } ); worker.ProgressChanged += new ProgressChangedEventHandler ( (object sender, ProgressChangedEventArgs e) => { Console.WriteLine($"任务进度: {e.ProgressPercentage}"); } ); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler ( (object sender, RunWorkerCompletedEventArgs e) => { if (e.Cancelled) Console.WriteLine($"任务取消,线程: {Thread.CurrentThread.ManagedThreadId}"); else Console.WriteLine($"任务完成,线程: {Thread.CurrentThread.ManagedThreadId}"); } ); worker.WorkerReportsProgress = true;//允许进度通知 worker.WorkerSupportsCancellation = true;//允许取消任务 worker.RunWorkerAsync(100); } private void btnCancelBackgroundWorker_Click(object sender, EventArgs e) { worker?.CancelAsync(); }
正常执行完成日志:
主线程:1 --------------- 执行复杂任务, 线程: 3 任务进度: 1 任务进度: 2 任务进度: 3 ... ... ... 任务进度: 98 任务进度: 99 任务进度: 100 --------------- 执行复杂任务结束. 任务完成,线程: 1
任务取消日志:
主线程:1 --------------- 执行复杂任务, 线程: 4 任务进度: 1 任务进度: 2 任务进度: 3 任务进度: 4 任务进度: 5 任务进度: 6 任务进度: 7 任务取消,线程: 1