开发者

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.D开发者_StackOverflow社区oWork += 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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜