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

限于喜欢 提交于 2020-01-03 10:58:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!