How do you set the UserState in the RunWorkerCompletedEventArgs object?

房东的猫 提交于 2019-12-05 00:03:33

Your Start method on the Worker class can set the Result property of the DoWorkEventArgs argument. Here's an example:

void Start(object sender, DoWorkEventArgs e)
{
   //Do your loop and other work.
   e.Result = this;
}

Then in the finish event handler, you can retrieve e.Result:

public void WorkerFinished(object sender, RunWorkerCompletedEventArgs e)
{
    //You should always check e.Cancelled and e.Error before checking e.Result!
    // ... even though I'm skipping that here

    Worker w = e.Result as Worker;
    if( w != null)
    {
        if (_onManagerEvent != null)
            _onManagerEvent(new ManagerEvent 
                    { 
                      EventDate = DateTime.Now, 
                      Message = String.Format("Worker {0} successfully ended."
                                              , w.ToString()) 
                    });
    }
}
lesscode

That UserState thing is a known bug in BackgroundWorker:

http://www.pluralsight-training.net/community/blogs/mike/archive/2005/10/21/15783.aspx (archive.org link…original link is dead)

What I've done in the past when I've been in your situation is either use RunWorkerCompletedEventArgs.Result (as Philip suggests), or, if possible, have my worker derive from BackgroundWorker (then I can add as much extra state as I want, and get the whole worker as the sender argument to the events raised by BackgroundWorker, while still being able to use Result for its intended purpose).

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