如何使用BackgroundWorker事件RunWorkerCompleted [英] How to use the BackgroundWorker event RunWorkerCompleted
问题描述
所有,我已经知道BackgroundWorker
在WinForm中处理多线程情况的基本用法.代码结构如下所示.
All,I already knew the basic usage the BackgroundWorker
to handle multiple thread case in the WinForm . And the code structure looks like below.
在应用程序的主线程中.只需启动BackgroundWork.
In the main thread of application. just start the BackgroundWork.
if (backgroundWorker1.IsBusy != true)
{
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync();
}
然后它将触发DoWork
事件.所以我们可以在那里做些事情.
Then it would fire the DoWork
event . So we can do something in there.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
......
// report progress.
worker.ReportProgress(iProgress);
....
}
然后,我们只需要处理ProgressChanged
事件即可显示BackgroundWorker的进度.
Then we just need to handle the ProgressChanged
event to show the BackgroundWorker progress.
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//show progress.
resultLabel.Text = (e.ProgressPercentage.ToString() + "%");
}
DoWork
完成或发生某些异常之后.事件RunWorkerCompleted
将被触发.
After DoWork
finished or some exception happened. the event RunWorkerCompleted
would be fired.
以下是我对此事件句柄的疑问.请帮助对其进行审查.谢谢.
Here comes my questions for this events handle. please help to review them. thanks.
我注意到在RunWorkerCompletedEventArgs e
中有一个名为结果"的属性,它的作用是什么?如何使用?
I noticed there is property named 'Result' in the RunWorkerCompletedEventArgs e
, What does it use for? How can I use it ?
是否有可能收到我的自定义异常消息而不是e.error
?如果有,如何制作?
Is there any possibility to receive my custom exception message instead the e.error
? If there is, How to make it ?
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
resultLabel.Text = "Canceled!";
}
else if (e.Error != null)
{
resultLabel.Text = "Error: " + e.Error.Message;
}
else
{
resultLabel.Text = e.Result.ToString();
}
}
推荐答案
RunWorkerCompletedEventArgs
中的Result
属性是您已分配给DoWork()
中DoWorkEventHandler
的Result属性的值.
The Result
property in RunWorkerCompletedEventArgs
is the value you have assigned to the Result property of DoWorkEventHandler
in DoWork()
.
您可以为此分配任何内容,因此您可以返回整数,字符串,对象/复合类型等.
You can assign anything you like to this, so you could return an integer, a string, an object/composite type, etc.
如果在DoWork()
中引发了异常,则可以在RunWorkerCompletedEventArgs
的Error
属性中访问该异常.在这种情况下,访问Result属性将导致引发TargetInvocationException
.
If an exception is thrown in DoWork()
then you can access the exception in the Error
property of RunWorkerCompletedEventArgs
. In this situation, accessing the Result property will cause an TargetInvocationException
to be thrown.
这篇关于如何使用BackgroundWorker事件RunWorkerCompleted的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!