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?