使用前提

在WPF程序中,有一些比较耗时的后台操作时,比如向远程服务器请求数据,或者通过TCP/IP为某台设备提供升级固件服务等等。为了防止这类操作freeze用户界面,造成用户体验下降,即程序假死的状况出现。一种常见的,更user friendly的方式是,提供一个进度条窗口,提示用户该操作的完成进度。并提供取消操作的选项。
C#中的 BackgroundWorker Class .aspx)则是执行该任务的最佳选择。

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, theBackgroundWorker class provides a convenient solution. -MSDN

关于 BackgroundWorker 类

主要属性

  • CancellationPending - 只读属性,default值为false,执行CancelAsync方法后,值为true。表明应用程序请求了取消后台操作。
  • IsBusy - 如果后台异步操作开始执行,值为true,否则为false
  • WorkerReportProgress - 如果BackgroundWorker支持后台操作进程更新,设置值为true,default值为false

主要事件

  • DoWork
  • ProgressChanged
  • RunWorkerCompleted
    不要再DoWork事件处理程序中对UI线程中的对象进行操作,操作应该放在ProgressChanged和RunWorkerCompleted的事件处理程序中。

主要方法

  • RunWorkerAsync() - 执行后台操作,激发DoWork事件
  • ReportProgress()- 激发ProgressChanged事件
  • CancelAsync() - 提交终止后台操作的请求,并将CancellationPending属性值设为true。在程序其他地方要定时检查CancellationPending属性的值,作出相应操作,比如
  1. if (worker.CancellationPending)
  2. {
  3. e.Cancel = true;
  4. }

示例程序

XAML

  1. <Window x:Class="BackgroundWorkerExample.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. Title="MainWindow" Height="150" Width="300">
  5. <StackPanel>
  6. <ProgressBar Name="progressBar" Height="20" Width="250" Margin="10"></ProgressBar>
  7. <TextBox Name="textBox" Width="50" Height="20" HorizontalAlignment="Center"></TextBox>
  8. <Button Name="btnProcess" Width="100" Click="btnProcess_Click" Margin="5">Start</Button>
  9. <Button Name="btnCancel" Width="100" Click="btnCancel_Click" Margin="5">Cancel</Button>
  10. </StackPanel>
  11. </Window>

C#

  1. namespace BackgroundWorkerExample
  2. {
  3. /// <summary>
  4. /// Interaction logic for MainWindow.xaml
  5. /// </summary>
  6. public partial class MainWindow : Window
  7. {
  8. BackgroundWorker bgworker = new BackgroundWorker();
  9. public MainWindow()
  10. {
  11. InitializeComponent();
  12. bgworker.WorkerReportsProgress = true;
  13. bgworker.WorkerSupportsCancellation = true;
  14. bgworker.DoWork += bgworker_DoWork;
  15. bgworker.ProgressChanged += bgworker_ProgressChanged;
  16. bgworker.RunWorkerCompleted += bgworker_RunWorkerCompleted;
  17. }
  18. void bgworker_DoWork(object sender, DoWorkEventArgs e)
  19. {
  20. BackgroundWorker worker = sender as BackgroundWorker;
  21. for (int i = 1; i <= 100; i++)
  22. {
  23. if (worker.CancellationPending)
  24. {
  25. e.Cancel = true;
  26. }
  27. else
  28. {
  29. worker.ReportProgress(i);
  30. Thread.Sleep(100);
  31. }
  32. }
  33. }
  34. void bgworker_ProgressChanged(object sender, ProgressChangedEventArgs e)
  35. {
  36. progressBar.Value = e.ProgressPercentage;
  37. textBox.Text = e.ProgressPercentage.ToString();
  38. }
  39. void bgworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  40. {
  41. progressBar.Value = 0;
  42. if (e.Cancelled)
  43. {
  44. MessageBox.Show("Background task has been canceled", "info");
  45. }
  46. else
  47. {
  48. MessageBox.Show("Background task finished", "info");
  49. }
  50. }
  51. private void btnProcess_Click(object sender, RoutedEventArgs e)
  52. {
  53. if (!bgworker.IsBusy)
  54. {
  55. bgworker.RunWorkerAsync();
  56. }
  57. }
  58. private void btnCancel_Click(object sender, RoutedEventArgs e)
  59. {
  60. bgworker.CancelAsync();
  61. }
  62. }
  63. }

演示

C# 使用C#中BackgroundWorker - 图1
BackgroundWorkerExample.gif

作者:Jason_Yuan
链接:https://www.jianshu.com/p/b89f39c5f803
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。