HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Passing variable to BackgroundWorker and use the same value later

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
samethelaterpassingvalueandbackgroundworkerusevariable

Problem

I create multiple BackgroundWorker within a for-loop and each of them needs to know a special value. To simplify, it is just i in this example. When the BackgroundWorker is finished, I need to read that i again. I thought of subclassing BackgroundWorker and creating a class MyBW for that purpose which is able to store the i as value.

My example below works, but I am interested, if this is the best way to do this?

Edit: I have to add, that the variable I need to pass is a simple String, not a large object.

Fully working minimal example

using System;
using System.Text;

namespace MultiThreadTest
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i 
        /// Here I store the value.
        /// 
        public int value;
    }
}

Solution

BackgroundWorker already has a mechanism for passing and retrieving arguments. The DoWorkEventArgs has a property for a passed in method argument and a property for the DoWork result. The RunWorkerCompletedEventArgs has a property for retrieving the result. No sub-classing is necessary, although you may need to make a custom container if you need to pass/return more than one object.

for (int i = 0; i < 10; i++)
{
  BackgroundWorker bw = new BackgroundWorker ();
  bw.WorkerReportsProgress = false;
  bw.DoWork += delegate(object sender, System.ComponentModel.DoWorkEventArgs eargs)
  {
    int i = (int)eargs.Arugment;  //get argument
    Console.WriteLine(String.Format("Thread {0} started", bw.value));
    System.Threading.Thread.Sleep(bw.value * 1000);
    eargs.Result = i;            //set result
  };
  bw.RunWorkerCompleted += delegate(object sender, System.ComponentModel.RunWorkerCompletedEventArgs eargs)
  {
    int i = (int)eargs.Arugment;  //get argument
    Console.WriteLine(String.Format("Thread {0} finished", i));
  };

  bw.RunWorkerAsync(i);
}

Code Snippets

for (int i = 0; i < 10; i++)
{
  BackgroundWorker bw = new BackgroundWorker ();
  bw.WorkerReportsProgress = false;
  bw.DoWork += delegate(object sender, System.ComponentModel.DoWorkEventArgs eargs)
  {
    int i = (int)eargs.Arugment;  //get argument
    Console.WriteLine(String.Format("Thread {0} started", bw.value));
    System.Threading.Thread.Sleep(bw.value * 1000);
    eargs.Result = i;            //set result
  };
  bw.RunWorkerCompleted += delegate(object sender, System.ComponentModel.RunWorkerCompletedEventArgs eargs)
  {
    int i = (int)eargs.Arugment;  //get argument
    Console.WriteLine(String.Format("Thread {0} finished", i));
  };

  bw.RunWorkerAsync(i);
}

Context

StackExchange Code Review Q#136092, answer score: 6

Revisions (0)

No revisions yet.