简体   繁体   中英

How can I ensure a specific background worker thread executes before another one?

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 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM