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?
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
AutoResetEventinstead. At the beginning of bw2’s code callev.WaitOne()and in bw1’swork_completedcallev.Set()to release bw2: