Is BackgroundWorker's IsBusy same as “IsAlive”?

人盡茶涼 提交于 2020-01-13 09:27:12

问题


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

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.

Can I count on IsBusy to do:

if (!myWorker.IsBusy)
  RestartWorker();

or am I calling for trouble?


回答1:


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.

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.




回答2:


To make sure the Backgroundworker really stopped, you can kill it manually. Set yourBackgroundWorker.WorkerSupportsCancellation = true;. Then simply stop the Backgroundworker with:

yourBackgroundWorker.CancelAsync();

Still isBusy should be enough to detect a running/working instance of your BackgroundWorker.




回答3:


From the docs:

true, if the BackgroundWorker is running an asynchronous operation; otherwise, false.

Regardless if you sleep the worker thread or not, it's still doing something so using IsBusy should be fine.



来源:https://stackoverflow.com/questions/13139691/is-backgroundworkers-isbusy-same-as-isalive

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