Question

I have a WPF application with two background worker threads that operate while loading.

The first one (bw1) is spawned at application start, and the second one (bw2) is spawned after some time has elapsed.

I am in a situation that I CAN'T spawn the second background worker (bw2) from the first one's (bw1) "worker_completed".

Currently, I have a class-level bool variable (default false), and set it true in bw1's worker_completed.

And at the starting of bw2, I have a check to see if the above bool is false, and if so, bw2 will sleep for 100 milliseconds.

This works, for the most part. I'd like to improve it.

  • Can I use thread priority in bw1 (set it as highest, say) to ensure that bw1 is executed while bw2 sleeps?

  • Is there an event-driven way I can accomplish this goal?

Was it helpful?

Solution

Busy spinning (even with sleep) is a bad idea when you don't actually know when the event will occur, since you are checking blindly and using system resources unnecessarily.

Use an AutoResetEvent instead. At the beginning of bw2's code call ev.WaitOne() and in bw1's work_completed call ev.Set() to release bw2:

AutoResetEvent ev = new AutoResetEvent();

// bw1's work completed     
private void bw1_workCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    ev.Set(); // release bw2 from waiting
}

// bw2's do work
private void bw2_DoWork(object sender, DoWorkEventArgs e)
{
    ev.WaitOne(); // wait for the signal from bw1
    // code
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top