此BackgroundWorker当前正忙,无法同时运行多个任务
如果我单击启动后台工作程序两次的按钮,我会收到此错误。
This BackgroundWorker is currently busy and cannot run multiple tasks concurrently
我怎样才能避免这种情况?
I get this error if I click a button that starts the backgroundworker twice.
This BackgroundWorker is currently busy and cannot run multiple tasks concurrently
How can I avoid this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简单:不要启动BackgroundWorker 两次。
您可以使用
IsBusy
属性检查它是否已经在运行,因此只需将此代码更改为:
更新:
如果您确实需要同时启动多个后台任务,您可以简单地创建多个BackgroundWorker对象
Simple: Don't start the BackgroundWorker twice.
You can check if it is already running by using the
IsBusy
property, so just change this code:to this:
Update:
If you do actually need to launch multiple background tasks at the same time, you can simply create multiple BackgroundWorker objects
为您要执行的每个操作创建一个新的BackgroundWorker 对象。 即,而不是:
试试这个:
Create a new BackgroundWorker object for each operation that you want to perform. I.e., rather than:
Try this:
我会考虑对需要完成的任务进行排队。 您将获得以下优势:
这是一个示例实现: 链接。 我不确定该实现是否是线程安全的,一旦我弄清楚我正在使用的实现中当前的锁定问题,我将更新我的答案。
I would look into queueing the tasks that need to be done. You get the following advantages:
Here is an example implementation: link. I am not sure if the implementation in threadsafe, and I will update my answer once I figure out of my current locking problem in a implementation I am working with.
虽然不是OP最初询问的情况,但如果您以某种生产者-消费者模式使用后台工作人员,这也可能由于竞争条件而发生(现在发生在我身上,并寻找答案)。
示例:
在这种情况下,存在竞争条件:第一个实例实例化一个新的后台工作线程,第二个实例到达
else if
并启动后台工作线程,然后第一个实例到达if< 的 RunWorkerAsync /code> 块,当它执行时它会抛出错误。
可以通过向整个 if + if else 部分添加锁来避免这种情况。
Although not the case originally asked by the OP, this can also happen due to a race condition (happened to me now, and looked for an answer) if you're using a Background worker in some sort of a producer-consumer pattern.
Example:
In this case there's a race condition: first instance instantiates a new background worker, 2nd instance reaches the
else if
and starts the background worker, before 1st instance reaches the RunWorkerAsync of theif
block, and when it does it throws the error.This can be avoided by adding a lock to the entire if + if else section.