问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/7432780/is-this-safe-to-unsubscribe-dowork-after-calling-runworkerasync-but-before-the-f