本文介绍了这是安全要求的RunWorkerAsync之后,但在函数退出前退订DoWork的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多方法,它们都使用(他们只在一个时间虽然运行一个)相同的 RunWorkerCompleated ProgressChanged 的方法,但它们都具有不同的的DoWork 的方法。是否安全,做到以下几点:

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

或者我可以打一个边缘的情况下这样做呢?我没有看到它说这是不允许的,它是(迄今为止)在我的程序运行良好的MSDN什么,但我想检查这里看看是否有人在麻烦这样运行。

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

和以任何处理您完成

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

我也不过感觉;它可能是更好的只是单独的 BackGroundWorkers 对自己的行为,你需要执行与共享类似的一个替代或包裹在一个类中,所以你可以更清楚自己在做什么。

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.

这篇关于这是安全要求的RunWorkerAsync之后,但在函数退出前退订DoWork的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 06:03