How to use the BackgroundWorker event RunWorkerCompleted

故事扮演 提交于 2019-12-01 16:45:40

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.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!