在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負責更新界面操作。