WPF线程(Step2)——BackgroundWorker

旧地址:http://blog.canself.com/thread_backgroudnworker/

在WPF中第二个常用的线程处理方式就是BackgroundWorker。

以下是BackgroundWorker一个简单的例子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public partial class MainWindow : Window
{
/// <summary>
/// 后台worker
/// </summary>
BackgroundWorker worker = new BackgroundWorker();

public MainWindow()
{
InitializeComponent();
worker.WorkerReportsProgress = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.ProgressChanged += worker_ProgressChanged;
this.btn_test.Click += btn_test_Click;
}

/// <summary>
/// 按钮点击
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btn_test_Click(object sender, RoutedEventArgs e)
{
worker.RunWorkerAsync();
}

/// <summary>
/// 进度返回处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.pb_test.Value = e.ProgressPercentage;
}

/// <summary>
/// 业务逻辑处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= 100; i++)
{
worker.ReportProgress(i);//返回进度
Thread.Sleep(100);
}
}
}

其中要注意的有BackgroundWorker的属性WorkerReportsProgress表示BackgroundWorker是否可以返回进度。事件DoWork中处理自身的业务逻辑,ProgressChanged负责更新界面操作。