在单个BackgroundWorker上运行多个DoWork功能是否安全? [英] Is it safe to run multiple DoWork functions on a single BackgroundWorker?

查看:83
本文介绍了在单个BackgroundWorker上运行多个DoWork功能是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用已建立的代码库,我想将正在完成的一些工作移到单独的线程中.当前代码的结构方式我想做类似的事情:

I'm working with an established code base and I'd like to move some of the work that's being done to a separate thread. The way the code is currently structured I'd like to do something like:

var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += firstFunctionToDoSomeWork;
backgroundWorker.DoWork += secondFunctionToDoSomeWork;
backgroundWorker.RunWorkerCompleted += theWorkerCompletedFunction;
backgroundWorker.RunWorkerAsync();

我希望两个DoWork函数按顺序运行,firstFunctionToDoSomeWorksecondFunctionToDoSomeWork启动之前运行并完成.这样做是否安全?当两个函数没有按顺序运行时,是否可能会发生冲突?我想我想知道的是BackgroundWorker将如何处理第二个DoWork函数.

I would like the the two DoWork functions to run in order, the firstFunctionToDoSomeWork running and finishing before the secondFunctionToDoSomeWork starts. Is it safe to do something like this? Or will I possibly get conflicts when the two functions don't run in order? I guess what I'm wondering is how the BackgroundWorker will handle the second DoWork function.

谢谢

推荐答案

您不应依赖事件处理程序来按特定顺序触发事件.在实际实践中,大多数实现都有一个定义的顺序(最常见的是添加处理程序的顺序),但是您不能确定对于任何特定事件都是如此,并且实际上从来没有明确定义在事件的文档中,这意味着它会随着时间的推移而变化.

You should not rely on event handlers to be fired by an event in a particular order. Most implementation, in actual practice, will have a defined order (the most common of which is the order in which the handlers are added), but you cannot be sure that this is case for any particular event, and it is virtually never explicitly defined in an event's documentation, meaning that it's something that's subject to change over time.

即使未定义顺序(但不是全部),大多数事件也会按顺序触发其处理程序.有些甚至甚至并行解雇他们的处理程序.您可以完全确定不会在这里发生这种情况,但是在一般情况下, 是为任意事件编写处理程序时要准备的东西.

Most events also fire their handlers sequentially, even if the order is not defined, but not all. Some even fire their handlers in parallel. You can be pretty confident that that won't happen here, but in the general case, it is something to be prepared for when writing handlers for an arbitrary event.

如果对顺序执行这两个功能很重要,则应添加一个处理程序,并在该处理程序中调用以下两个方法:

If it's important for you to perform these two functions sequentially then you should add one handler, and in that handler you should call these two methods:

backgroundWorker.DoWork += (s, args) => 
{
    firstFunctionToDoSomeWork(s,args);
    secondFunctionToDoSomeWork(s,args);
};

这篇关于在单个BackgroundWorker上运行多个DoWork功能是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆