How to make BackgroundWorker return an object

Clair Vengs picture Clair Vengs · Jun 2, 2009 · Viewed 62.4k times · Source

I need to make RunWorkerAsync() return a List<FileInfo>. How can I return an object from a background worker?

Answer

David picture David · Jun 2, 2009

In your DoWork event handler for the BackgroundWorker (which is where the background work takes place) there is an argument DoWorkEventArgs. This object has a public property object Result. When your worker has generated its result (in your case, a List<FileInfo>), set e.Result to that, and return.

Now that your BackgroundWorker has completed its task, it triggers the RunWorkerCompleted event, which has a RunWorkerCompletedEventArgs object as an argument. RunWorkerCompletedEventArgs.Result will contain the result from your BackgroundWorker.

example:

private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
    int result = 2+2;
    e.Result = result;
}

private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    int result = (int)e.Result;
    MessageBox.Show("Result received: " + result.ToString());
}