后台线程,BackgroundWorker
类用于创建一个线程,在后台持续运行以完成某项工作,并不时地与主线程通信。
BackgroundWorker
类的属性,方法与事件。
属性:
WorkerReportsProgress
:设置后台任务是否可以把它的进度汇报给主线程。WorkerSupportsCancellation
:是否支持从主线程取消。IsBusy
:检查后台任务是否正在运行。CancellationPending
:每隔一段时间会检查该属性是否停止处理。
事件:
DoWork
- 在后台线程开始时触发。ProgressChanged
- 后台任务汇报进度时触发。RunWorkerCompleted
- 后台工作线程退出时触发。
方法:
RunWorkerAsync()
- 获取后台线程并执行 DoWork 事件处理程序。CancelAsync()
- 设置CancellationPending
属性为true。DoWork()
- 事件处理程序希望向主线程序汇报进度的时候,调用 ReportProgress 方法。
1 namespace WpfApp1 2 { 3 /// <summary> 4 /// MainWindow.xaml 的交互逻辑 5 /// </summary> 6 public partial class MainWindow : Window 7 { 8 BackgroundWorker bgWorker = new BackgroundWorker(); 9 public MainWindow() 10 { 11 InitializeComponent(); 12 // 初始化 13 bgWorker.WorkerReportsProgress = true; 14 bgWorker.WorkerSupportsCancellation = true; 15 16 // 事件注册 17 bgWorker.DoWork += DoWork_Handler; 18 bgWorker.ProgressChanged += ProgressChanged_Handler; 19 bgWorker.RunWorkerCompleted += RunWorkerCompleted_Handler; 20 } 21 22 private void RunWorkerCompleted_Handler(object sender, RunWorkerCompletedEventArgs e) 23 { 24 progressBar.Value = 0; 25 if (e.Cancelled) 26 MessageBox.Show("Process was cancelled.", "Process Cancelled"); 27 else 28 MessageBox.Show("Process completed normally.", "Process Completed"); 29 } 30 31 private void ProgressChanged_Handler(object sender, ProgressChangedEventArgs e) 32 { 33 // 设置进度条值 34 progressBar.Value = e.ProgressPercentage; 35 } 36 37 private void DoWork_Handler(object sender, DoWorkEventArgs e) 38 { 39 BackgroundWorker worker = sender as BackgroundWorker; 40 41 for (int i = 0; i <= 10; i++) 42 { 43 // 循环判断 CancellationPending 是否为true。 44 if (worker.CancellationPending) 45 { 46 e.Cancel = true; 47 break; 48 } 49 else 50 { 51 // 触发主线程 ProgressChanged 52 worker.ReportProgress(i * 10); 53 Thread.Sleep(250); 54 } 55 56 } 57 } 58 59 private async void btnProcess_Click(object sender, RoutedEventArgs e) 60 { 61 // 判断当前后台线程是否运行 62 if (!bgWorker.IsBusy) 63 // 调用方法启动后台线程,并触发 DoWork 事件 64 bgWorker.RunWorkerAsync(); 65 } 66 67 private void btnCancel_Click(object sender, RoutedEventArgs e) 68 { 69 // 设置对象 CancelltionPending 为true; 70 bgWorker.CancelAsync(); 71 } 72 } 73 }
标签:异步,RunWorkerCompleted,C#,DoWork,bgWorker,BackgroundWorker,Handler,线程 From: https://www.cnblogs.com/icecokelulu/p/18446407