Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this safe to unsubscribe DoWork after calling RunWorkerAsync but before the function exits?

I have many methods (they only run one at a time though), they all use the same RunWorkerCompleated and ProgressChanged methods but they all have different Dowork methods. Is it safe to do the following:

private void button_Process_Click(object sender, EventArgs e)
{
    bgWork_Process.DoWork += Scrub_DoWork;
    bgWork_Process.RunWorkerAsync();
    bgWork_Process.DoWork -= Scrub_DoWork;
}

or can I hit a edge case doing this? I did not see anything on the MSDN on it saying it was not allowed and it as (so far) run fine in my program, but I wanted to check here to see if anyone has run in to trouble doing this.

like image 299
Scott Chamberlain Avatar asked Sep 15 '11 14:09

Scott Chamberlain


1 Answers

What you could do to make sure that the Event Handler isn't being removed until you are done with it would be to do something similar to

Action DoWorkAction;

private void button_Process_Click(object sender, EventArgs e)
{
    gbHistory.Enabled = false;
    gbScrub.Enabled = false;
    DoWorkAction = new Action(Scrub_DoWork);
    bgWork_Process.DoWork += DoWorkAction;
    bgWork_Process.RunWorkerAsync();
}

And in whatever handles your completion

private void bgWork_Process_CompletedHandler(object sender, EventArgs e)
{
    bgWork_Process.DoWork -= DoWorkAction;
}

I do feel, however; that it may be better to just have separate BackGroundWorkers for all of your Actions that you need to perform instead of sharing a similar one with that or wrap in a class so you can be more clear about what you are doing.

like image 104
msarchet Avatar answered Oct 10 '22 06:10

msarchet