Is BackgroundWorker's IsBusy same as "IsAlive"?

scatmoi picture scatmoi · Oct 30, 2012 · Viewed 9.4k times · Source

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?

Answer

Hans Passant picture Hans Passant · Oct 30, 2012

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.