Background worker, passing and returning multiple parameters

Posted: 19th July 2010 by thegrayzone in Development
Tags:

I had a long running method that I decided to use the BackgroundWorker class to process. This process that the BackgroundWorker was running required multiple parameters to be passed to it, and it also returned multiple parameters back in the Completed method.

Rather than create a custom object like I had done in the past this time I decided to use the Tuple object to pass the multiple parameters.

Tuple Object

The Tuple object is very handy as it allows you to create a strongly typed object of up to 8 objects using the .Create() helper method, or if you need more than 8 objects you can use the standard constructor.

The Code

Below is some sample code, starting a BackgroundWorker object that takes in an integer, DateTime and a boolean. Once the background worker object has finished it returns a custom object, boolean and string.
Items within a Tuple object are accessed using the syntax:

myTuple.Item1;
myTuple.Item2;
using System;
using System.ComponentModel;

private void StartBackgroundWorker()
{
  BackgroundWorker worker = new BackgroundWorker();

  worker.DoWork += new DoWorkEventHandler(worker_DoWork);
  worker.RunWorkerCompleted += new  RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
  
  // Declare Tuple object to pass multiple params to DoWork method.
  var params = Tuple.Create<int, DateTime, bool>(44, DateTime.Now, false);
  worker.RunWorkerAsync(params);
}

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
  // Get Tuple object passed from RunWorkerAsync() method
  Tuple<int, DateTime, bool> params = e.Argument as Tuple<int, DateTime, bool>

  // Do some long running process
  
  // Set the result using new Tuple object to pass multiple objects to completed event handler
  e.Result = Tuple.Create<CustomObject, bool, string>(customObj, true, "hello");
}

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  // Get result objects
  Tuple<CustomObject, bool, string> res = e.Result as Tuple<CustomObject, bool, string>
}
  1. Richard says:

    I follow this up to the Tuple.Create>customObject…
    I don’t have a custom object. I have a method to call…
    can I still use a tuple?

  2. Mohanlal says:

    Is there any other way of passing arguments rather than using tuple???

  3. thegrayzone says:

    Hi Mohanlal,

    Thanks for the comment. Yes you can pass any object that you like to the RunWorkerAsync method as it takes an object. The only restriction is that you can only pass a single object. Rather than a tuple you could create a custom class which contains the values that you want to pass and cast e.Result from RunWorkerCompleted to whichever object you pass in.

    Hope that helps!

  4. mohanlal says:

    Yes tried it works thanks for help