How to make BackgroundWorker return an object

C#ConcurrencyAsynchronousBackgroundworkerWorker Process

C# Problem Overview


I need to make RunWorkerAsync() return a List<FileInfo>.

What is the process to be able to return an object from a background worker?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

I'm assuming that you don't want to block and wait on RunWorkerAsync() for the results (if you did, there would be no reason to run async!

If you want to be notified when the background process finishes, hook the RunWorkerCompleted Event. If you want to return some state, return it in the Result member of DoWork's event args.

Example:



private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
  // do your thing
  ....
  // return results
  e.Result = theResultObject;
}

// now get your results
private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  MyResultObject result = (MyResultObject)e.Result;
  // process your result...
}





Solution 3 - C#

RunWorkerAsync() starts the process asynchronously and will return and continue executing your code before the process actually completes. If you want to obtain the result of the BackgroundWorker, you'll need to create an instance variable to hold that value and check it once the BackgroundWorker completes.

If you want to wait until the work is finished, then you don't need a BackgroundWorker.

Solution 4 - C#

To add to David's answer, one may want to push a tuple through to provide more than one argument to the methods.

To do so let me update his answer, where a value (called engagementId) is passed through each of the calls and the tuple holds that original item for use as well as the result.

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

private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    (int engagementId, int result) tupleResult = ((int, int)) e.Result; // Both (( are needed for tuple/casting.

    MessageBox.Show($"Result received {tupleResult.result} for engagement {tupleResult.engagementId}");
}

See the answer to How To Cast To A Tuple for more information.

Solution 5 - C#

Depending on your model, you either want to have your worker thread call back to its creator (or to some other process) when it's finished its work, or you have to poll the worker thread every so often to see if it's done and, if so, get the result.

The idea of waiting for a worker thread to return its result undermines the benefits of multithreading.

Solution 6 - C#

You could have your thread raise an event with the object as an argument:

ThreadFinishedEvent(this, new ThreadEventArgs(object));

where:

public class ThreadEventArgs : EventArgs
{
    public ThreadEventArgs(object object)
    {
        Object = object
    }

    public object Object
    {
        get; private set;
    }
}

Solution 7 - C#

Generally speaking when running a process async, The worker thread should call a delegate or fire an event (like ChrisF).

You can check out the new PFX which has some concurrency function that can return values.

For example there is a function called Parallel.ForEach() which has an overload that can return a value.

check this out for more info

http://msdn.microsoft.com/en-us/magazine/cc817396.aspx">http://msdn.microsoft.com/en-us/magazine/cc817396.aspx</a>

Solution 8 - C#

Instead of doing the background work in the "DoWork" method, create a method that returns the type you want to return and apply that to e.Result as other answers here recommend. As a minimal example that answers the OP's question without overcomplicating the matter...

        private List<FileInfo> FileInfoWorker(object sender, DoWorkEventArgs e)
    {
        return new List<FileInfo>(new DirectoryInfo("C:\\SOTest").GetFiles().ToList());
    }

    private void bgwTest_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;

        e.Result = FileInfoWorker(worker, e);
    }

    private void bgwTest_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            MessageBox.Show(e.Error.Message);
        }
        else if (e.Cancelled)
        {
            tbStatus.Text = "Background operation cancelled.";
        }
        else
        {
            tbStatus.Text = "Background operation complete.";
        }
    }

The example also shows how to update a TextBox from the BackgroundWorker API. Not shown is support for reporting progress via a ProgressBar and TextBoxes and support for cancellation, both are also supported in the API. The code is ran via a button...

        private void btnSOTest_Click(object sender, EventArgs e)
    {
        bgwTest.RunWorkerAsync();
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionClair VengsView Question on Stackoverflow
Solution 1 - C#DavidView Answer on Stackoverflow
Solution 2 - C#JMarschView Answer on Stackoverflow
Solution 3 - C#Adam RobinsonView Answer on Stackoverflow
Solution 4 - C#ΩmegaManView Answer on Stackoverflow
Solution 5 - C#WelbogView Answer on Stackoverflow
Solution 6 - C#ChrisFView Answer on Stackoverflow
Solution 7 - C#SrulyView Answer on Stackoverflow
Solution 8 - C#jinzaiView Answer on Stackoverflow