Can I wait for a specific background thread finish, then another background thread starts? [closed]
Can I wait for a specific background thread finish, then another background thread starts?
In .NET 4, you can use Task instead of threads, and then use continuations to achieve your goals:
var firstTask = Task.Factory.StartNew( () => PerformSomeLongRunningAction(); );
var secondTask = firstTask.ContinueWith( t => PerformSecondAction(); );
In .NET <=3.5, the options vary. The best is often to use a WaitHandle to signal your second task. The first background thread will need to signal the wait handle when it's complete:
var mre = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem( o =>
{
PerformSomeLongRunningAction();
mre.Set(); // Signal to second thread that it can continue
});
ThreadPool.QueueUserWorkItem( o =>
{
mre.WaitOne(); // Wait for first thread to finish
PerformSecondAction();
});
Sure. Have the first thread launch the second thread, or set some sort of flag telling the hosting app to start the second thread. Of course, I have to ask: if these threads always run sequentially, why create a second thread at all instead of performing all of your work in the first thread?
Yes.
And if you provide more information, we can provide more detail in the answer.
In general, you set up a communication system (a message queue, Event, or delegate) that is used to signal that a process/step/thread is done. When that happens, start up the next thread.
精彩评论