[C#.NET] 如何 使用 BackgroundWorker 多執行緒 / 跨執行緒 存...

来源:百度文库 编辑:神马文学网 时间:2024/07/03 08:41:49
<< [C#.NET] 如何 使用 多執行緒 Thread / 跨執行緒 存取UI |Home |[C#.NET] 如何 使用 委派 Delegate / 事件 event >>
[C#.NET] 如何 使用 BackgroundWorker 多執行緒 / 跨執行緒 存取UI
在上一篇[C#.NET] 如何 使用 多執行緒 Thread / 跨執行緒 存取UI介紹了使用Thread來跨執行緒,這篇來記錄一下使用BackgroundWorker 控件的方法。
如何使用BackgroundWorker控件
1.在winfrom裡拖拉一個BackgroundWorker控件至from裡

2.使用RunWorkerAsync方法,將會觸動DoWork事件
this.backgroundWorker1.RunWorkerAsync(count);
3.在DoWork事件的方法中調用需要執行的方法
4.在方法中傳遞BackgroundWorker參數
5.允許BackgroundWorker報告進度
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { //4.在方法中傳遞BackgroundWorker參數 RunSample04(sender as BackgroundWorker);  //5.允許BackgroundWorker報告進度 this.backgroundWorker1.WorkerReportsProgress = true; this.progressBar1.Maximum = count; }
6.執行ReportProgress方法,觸發ProgressChanged事件
private void RunSample04(BackgroundWorker myWork) { myStr = ""; for (int i = 1; i <= count; i++) { try { //6.執行ReportProgress方法,觸發ProgressChanged事件 myWork.ReportProgress(i); myStr = i.ToString(); } catch (Exception ex) { Console.WriteLine(ex.Message); }  Thread.Sleep(1); Application.DoEvents(); } }
7.ProgressChanged事件顯示,回傳執行結果
//在ProgressChanged事件的方法中顯示進度 private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { try { //7.回傳執行結果 this.textBox2.Text = myStr; this.progressBar1.Value = e.ProgressPercentage; Thread.Sleep(1); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
8.RunWorkerCompleted事件顯示,執行完成結果
//在RunWorkerCompleted事件的方法中顯示被執行方法的結果 private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //if (e.Error != null) //{ // MessageBox.Show(e.Error.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); // return; //} //else if (e.Cancelled) //{ // MessageBox.Show("取消操作!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); // return; //} //else //{ // MessageBox.Show("操作成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); //} }
執行結果:

C#範例:C#.NET多執行緒.rar
分享
新手發帖請多包涵

',1)">
',2)">
2009/2/15 13:17| 閱讀數 : 12649 |2 人收藏 我要推薦 |4 Comments | 文章分類:C#.NET |訂閱
關連文章
[C#.NET] 如何 使用 WinForm 關閉 視窗 事件[C#.NET] 如何 使用 委派 Delegate / 事件 event[C#.NET] 如何 使用 多執行緒 Thread / 跨執行緒 存取UI[C#.NET]使用圖片