BackgroundWorker的IsBusy是否与“ IsAlive”相同? [英] Is BackgroundWorker's IsBusy same as "IsAlive"?

查看:348
本文介绍了BackgroundWorker的IsBusy是否与“ IsAlive”相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出一种方法来验证BackgroundWorker线程是否还处于活动状态(即仍在运行。该线程实质上是作为简单的无限循环实现的:

I am trying to figure out a way to verify that a BackgroundWorker thread is alive (i.e. still running. The thread is essentially implemented as a simple infinite loop:

while (AllConditionsMet())
{
  DoSomeMagic();
  Thread.Sleep(10000);
}

到目前为止,我发现与 IsAlive()最接近的是< a href = http://msdn.microsoft.com/zh-cn/library/system.componentmodel.backgroundworker.isbusy%28v=vs.100%29.aspx rel = nofollow> IsBusy 属性,但考虑到我的线程Sleep()大部分时间都是我的,我不确定这是否能完成工作。

The closest thing to IsAlive() I found so far is the IsBusy property, but given that my thread Sleep()s most of the time, I am not sure whether this will do the job.

我可以依靠 IsBusy 来做:

if (!myWorker.IsBusy)
  RestartWorker();

还是我在找麻烦?

推荐答案

<$ C只要DoWork事件处理程序忙于并且尚未运行RunWorkerCompleted事件处理程序,则$ c> BackgroundWorker.IsBusy 为true。请注意后面的子句,该属性告诉您循环是否处于活动状态。

BackgroundWorker.IsBusy is true as long as the DoWork event handler is busy and the RunWorkerCompleted event handler hasn't been run yet. Do note the latter clause, the property does not tell you if your loop is active.

此外,第二个片段中还存在相当恶劣的比赛条件。 IsBusy在 if()语句中可能为true,但在一纳秒后为false。每月举行一次的比赛。代码的意图很难从代码片段中了解,因此很难给出解决方法。考虑始终创建一个永远不会竞争的新BGW对象。还有助于摆脱该循环,休眠10秒钟的线程在无所事事上浪费了非常昂贵的系统资源。并且它会破坏线程池调度程序。

Furthermore, there's a fairly nasty race condition in your second snippet. IsBusy might be true in the if() statement but be false a nanosecond later. The kind of race that strikes once a month. The intent of the code is hard to fathom from the snippets so hard to give a workaround. Consider just always creating a new BGW object, that will never race. Also helps getting rid of that loop, a thread sleeping for 10 seconds is wasting a very expensive system resource on doing nothing. And it gums-up the threadpool scheduler.

这篇关于BackgroundWorker的IsBusy是否与“ IsAlive”相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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