开发者

Using parameters in BackgroundWorker handlers

开发者 https://www.devze.com 2023-03-13 03:56 出处:网络
For passing data to a BackgroundWorker\'s DoWork I use a separate wrapper class\' instance: MyParams mpar = new MyParams();

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?
        }
        ));
    }


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号