BackgroundWorkers never stop being busy

Marcelo picture Marcelo · Feb 2, 2010 · Viewed 18.4k times · Source
for (do it a bunch of times)
{         
    while (backgroundWorker1.IsBusy && backgroundWorker2.IsBusy &&
           backgroundWorker3.IsBusy && backgroundWorker4.IsBusy &&
           backgroundWorker5.IsBusy)
    {
        System.Threading.Thread.Sleep(0001);
    }

    if (!backgroundWorker1.IsBusy)
    {
        backgroundWorker1.RunWorkerAsync();
    }
    else if (!backgroundWorker2.IsBusy)
    {
        backgroundWorker2.RunWorkerAsync();
    }
    else if (!backgroundWorker3.IsBusy)
    {
        backgroundWorker3.RunWorkerAsync();
    }
    else if (!backgroundWorker4.IsBusy)
    {
        backgroundWorker4.RunWorkerAsync();
    }
    else if (!backgroundWorker5.IsBusy)
    {
        backgroundWorker5.RunWorkerAsync();
    }
}

it runs five times (every BG-worker once) and gets stuck in the while. Don't the backgroundworkers ever stop being busy ? how do I check availability ?

note: there are 5 worker threads, this assures none of them is ever stopped, always assigning work to them. But they refuse to tell me when they are available, I thought that would have a simple solution..

--[edit request]---

Actually it was only a dummy parameter, i removed it and forgot to get it out, I only use it to call the dowork, who does the dirty job:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    timeconsumingfunction(publicstring);
}

And the timeconsumingfunction DOES end. stepping into it in the debugger and running line per line, it goes until the end and arrives in the final '}'. That means it ends, right ?

---[EDIT ANSWER]---- it worked by JUST replacing the line

System.Threading.Thread.Sleep(0001);

with

Application.DoEvents();

I guess it would run the background, but not receive the answer and not update the IsBusy tags.

Thanks everybody, great answers, helped a lot!

Answer

Hans Passant picture Hans Passant · Feb 2, 2010

Your loop is causing deadlock, the BGWs cannot complete. The problem is the RunWorkerCompleted event, it is raised on the UI thread. That bit of BGW magic requires the UI thread to be idle, it must be pumping its message loop. Problem is, the UI thread is not idle and it isn't pumping messages, it is stuck in the for loop. Thus, the event handler cannot run and IsBusy stays true.

You'll need to do this differently. Leverage the RunWorkerCompleted event to run the code that you'd normally run after this for loop. Resist all temptation to call Application.DoEvents() inside the loop.