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

来源:互联网 发布:pop3协议端口 编辑:程序博客网 时间:2024/05/16 08:43

http://www.dotblogs.com.tw/yc421206/archive/2009/02/15/7174.aspx

如何使用BackgroundWorker控件

1.在winfrom裡拖拉一個BackgroundWorker控件至from裡

快照-200921543422

 

 

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);
//}
}

 

執行結果:

 

 

 

快照-2009215566
原创粉丝点击