C# 如何使用 BackgroundWorker 事件 RunWorkerCompleted

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19723742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:44:27  来源:igfitidea点击:

How to use the BackgroundWorker event RunWorkerCompleted

c#winformsbackgroundworker

提问by Joe.wang

All,I already knew the basic usage the BackgroundWorkerto handle multiple thread case in the WinForm . And the code structure looks like below.

所有,我已经知道BackgroundWorker在 WinForm 中处理多线程情况的基本用法。代码结构如下所示。

In the main thread of application. just start the BackgroundWork.

在应用程序的主线程中。只需启动BackgroundWork。

    if (backgroundWorker1.IsBusy != true)
    {
        // Start the asynchronous operation.
        backgroundWorker1.RunWorkerAsync();
    }

Then it would fire the DoWorkevent . So we can do something in there.

然后它会触发DoWork事件。所以我们可以在里面做点什么。

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    ......
    // report progress.
    worker.ReportProgress(iProgress);
    ....
}

Then we just need to handle the ProgressChangedevent to show the BackgroundWorker progress.

然后我们只需要处理ProgressChanged事件来显示BackgroundWorker的进度。

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    //show progress.   
    resultLabel.Text = (e.ProgressPercentage.ToString() + "%");
}

After DoWorkfinished or some exception happened. the event RunWorkerCompletedwould be fired.

完成DoWork后或发生了一些异常。该事件RunWorkerCompleted将被解雇。

Here comes my questions for this events handle. please help to review them. thanks.

这是我对这个事件句柄的问题。请帮助它们。谢谢。

I noticed there is property named 'Result' in the RunWorkerCompletedEventArgs e, What does it use for? How can I use it ?

我注意到 中有一个名为“Result”的属性RunWorkerCompletedEventArgs e,它有什么用?我怎样才能使用它?

Is there any possibility to receive my custom exception message instead the e.error? If there is, How to make it ?

是否有可能收到我的自定义异常消息而不是e.error?如果有,如何制作?

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

采纳答案by SimonGoldstone

The Resultproperty in RunWorkerCompletedEventArgsis the value you have assigned to the Result property of DoWorkEventHandlerin DoWork().

Result物业RunWorkerCompletedEventArgs是已分配给的结果属性的值DoWorkEventHandlerDoWork()

You can assign anything you like to this, so you could return an integer, a string, an object/composite type, etc.

你可以为它分配任何你喜欢的东西,所以你可以返回一个整数、一个字符串、一个对象/复合类型等。

If an exception is thrown in DoWork()then you can access the exception in the Errorproperty of RunWorkerCompletedEventArgs. In this situation, accessing the Result property will cause an TargetInvocationExceptionto be thrown.

如果抛出异常,DoWork()则可以访问 的Error属性中的异常RunWorkerCompletedEventArgs。在这种情况下,访问 Result 属性将导致TargetInvocationException抛出an 。

回答by Dimith

You can use the Result property to store any results from the DoWork and access it from Completed event. But if the background worker process got cancelled or an exception raised, the result won't be accessible. You will find more details here.

您可以使用 Result 属性存储来自 DoWork 的任何结果并从 Completed 事件访问它。但是,如果后台工作进程被取消或引发异常,则将无法访问结果。您将在此处找到更多详细信息。

回答by Franck

public class MyWorkerClass
{
    private string _errorMessage = "";
    public string ErrorMessage { get { return _errorMessage; } set { _errorMessage = value; }}

    public void RunStuff(object sender, DoWorkEventArgs e)
    {
        //... put some code here and fill ErrorMessage whenever you want
    }
}

then the class where you use it

然后是您使用它的课程

public class MyClassUsingWorker
{
    // have reference to the class where the worker will be running
    private MyWorkerClass mwc = null;

    // run the worker
    public void RunMyWorker()
    {
        mwc = new MyWorkerClass();
        BackgroundWorker backgroundWorker1 = new BackgroundWorker();
        backgroundWorker1.DoWork += new DoWorkEventHandler(mwc.RunStuff);
        backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
        backgroundWorker1.RunWorkerAsync();
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        string strSpecialMessage = mwc.ErrorMessage;

        if (e.Cancelled == true)
        {
            resultLabel.Text = "Canceled!";
        }
        else if (e.Error != null)
        {
            resultLabel.Text = "Error: " + e.Error.Message;
        }
        else
        {
            resultLabel.Text = e.Result.ToString();
        }
    }
}