0
Reply

Backgroundworker Thread Being Starved

sam

sam

Oct 29 2008 4:42 PM
5.9k
I am having some trouble with a backgroundworker ("bw'r" for short) being starved while the main thread is in a loop. I have tried a few different tricks to give the bw'r a few cpu cycles, but to no avail thus far. Below is a snippet explaining some of the setup.

Within the 'test()' function on the main thread I have tried a number of techniques to give some time to 'backgroundworker_DoWork()', but no matter what while test() is within its loop the bw'r does not seem to run. Within 'test()' I have tried different sleep values (0, 1, 250, 5000), taking the sleep out entirely, changing the bw'r to a normal thread and increasing its priority, and finally using DoEvents within 'test()'. Thus far only DoEvents has helped anything, but I have read that this is not a proper solution.

I have a guess that I need to add another bw'r to replace test() and notify the main form upon completion, however I also need to understand why the below scenario is not working. Am I missing some idiosyncrasy of threads and bw'rs? Note that there are a few more app's running around in my app, but the only time the bw'r freezes is during this function. Thanks.

// method main form application
void test()
{
  // loop taking anywhere from 10 seconds to 10 minutes
  while(!found)
  {
    // do work, look for results
    Thread.Sleep(1); // sleep doesn't seem to help
    // Application.DoEvents(); // only thing that seems to work
  }
}


// separate thread using backgroundworker control
void backgroundworker_DoWork(....)
{
  // loop taking approx 1.5 seconds to complete
  while(true)
  {
    // communicate with h/w and update shared values
    Thread.Sleep(1);
  }
}