The Grayzone

Background Worker, Passing and Returning Multiple Parameters

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:

csharp myTuple.Item1; myTuple.Item2; csharp

```csharp 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> } ```csharp

Share this: