在WPF中第二个常用的线程处理方式就是BackgroundWorker。
以下是BackgroundWorker一个简单的例子。
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负责更新界面操作。
项目托管地址:https://wpfthread.codeplex.com/
原文:http://www.cnblogs.com/huaxia283611/p/4185733.html