代码:
static void Main(string[] args) { BackgroundWorker bw = new BackgroundWorker(); bw.WorkerReportsProgress = true; bw.WorkerSupportsCancellation = true; bw.DoWork += Worker_doWork; bw.ProgressChanged += Worker_ProcessChanged; bw.RunWorkerCompleted += Worker_Completed; bw.RunWorkerAsync(); Console.WriteLine("Press C to Cancel"); do { if (Console.ReadKey(true).KeyChar == 'C') { bw.CancelAsync(); } } while (bw.IsBusy); } static void Worker_doWork(object sender, DoWorkEventArgs e) { Console.WriteLine("当前线程ID:{0}", Thread.CurrentThread.ManagedThreadId); BackgroundWorker bw = (BackgroundWorker)sender; for (int i = 1; i <= 100; i++) { if (bw.CancellationPending == true) { e.Cancel = true; return; } if (i % 10 == 0) { bw.ReportProgress(i); } Thread.Sleep(TimeSpan.FromSeconds(0.1)); } e.Result = 42; } static void Worker_ProcessChanged(object sender, ProgressChangedEventArgs e) { Console.WriteLine("%{0} is Completed. process thread pool thread id {1}", e.ProgressPercentage, Thread.CurrentThread.ManagedThreadId); } static void Worker_Completed(object sender, RunWorkerCompletedEventArgs e) { Console.WriteLine("完成的线程ID:{0}",Thread.CurrentThread.ManagedThreadId); if (e.Error != null) { Console.WriteLine(e.Error.Message); } else if (e.Cancelled) { Console.WriteLine("Operation has been canceled"); } else { Console.WriteLine("The Answer is {0}:",e.Result); } }
运行结果: