Using parameters in BackgroundWorker handlers

rem picture rem · Jun 16, 2011 · Viewed 10.9k times · Source

For passing data to a BackgroundWorker's DoWork I use a separate wrapper class' instance:

MyParams mpar = new MyParams();
...
mpar.Par1 = par1val;
mpar.Par2 = par2val;
mpar.Par3 = par3val;
...
var worker1 = new System.ComponentModel.BackgroundWorker();
worker1.DoWork += new DoWorkEventHandler(worker1_DoWork);
worker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker1_RunWorkerCompleted);
worker1.RunWorkerAsync(mpar);

Then I can use parameters of mpar instance in worker1_DoWork, operating in another thread.

void worker1_DoWork(object sender, DoWorkEventArgs e)
 {
      //here we use mpar.Par1, mpar.Par2 and so on
 }

In RunWorkerCompletedEventHandler we do some postactions in UI thread.

My question is : Can we use in RunWorkerCompleted handler the mpar instance, which worked just before in DoWork handler and can we be sure its values are the same it had in DoWork? If not, what is the correct approach for sharing parameters for various stages of BackgroundWorker operation?

void worker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Dispatcher.BeginInvoke((Action)(() =>
        {
            //Can we use the mpar instance here?
        }
        ));
    }

Answer

oleksii picture oleksii · Jun 16, 2011

You can assign the value of e.Result in worker1_DoWork

static void worker1_DoWork(object sender, DoWorkEventArgs e)
{
    //Do the work
    //...

    e.Result = new MyParams();
}

Then you can get it in the worker1_RunWorkerCompleted in e.Result.

If you need to pass additional result value and you don't want to put MyParams object in the worker1_DoWork: e.Result - then you can create a small class ResultHolder with MyParams and MyResult as properties and use that class to pass the result in worker1_DoWork