views:

179

answers:

2

What is the standard way to wait on a process in another thread to complete?

In my case I have a multi-threaded service, and I want to ensure that when a service stop is requested that processing completes before service exits. Should I use a ManualResetEvent?

+2  A: 

You could keep a List and when the service is stopped call Thread.Join on each of them in turn. This would wait until every one had exitted.

JDunkerley
+1  A: 

If you have a reference to the threads you're waiting to finish you can call the .Join() method on those references. This will cause your main thread to wait until the threads you've called .Join() on to finish before it proceeds.

Alternatively you could create an array of ManualResetEvents that both your main thread and child thread have access to. Each child thread has a reference to one event in the array the main thread has access to. Call WaitHandle.WaitAll(array of events) on event array at end of main thread, and call .Set() on event at end of each child thread to signal main thread child threads are done.

Before main thread exits, below will block until all child threads calls .Set() on their events:

WaitHandle.WaitAll(array of events);

Binz
Bear in mind that WaitAll will only allow up to 64 handles to wait on.In the service stop event handler you may need to iterate over all events and call WaitOne explicitly on all handles
Abhijeet Patel
Actually combined Thread.Interupt and Thread.Join
C. Ross