THX-1138 THX-1138 - 3 months ago 34
C# Question

Join threads from thread pool

I have 30+ tasks that can be executed in parallel.

I use ThreadPool for each task.

But parent-function should not return until all tasks has completed.

I need a thread sync handle that would release WaitOne when its count reaches 0.
Something like:

foo.StartWith(myTasks.Count);
foreach (var task in myTasks) {
ThreadPool.QueueUserWorkItem(state => { task(state); foo.Release(); });
}
foo.WaitOne();


Semaphore
feels right, just can't figure out how to apply it here.

Answer
int running = myTasks.Count;
AutoResetEvent done = new AutoResetEvent(false);
foreach (var task in myTasks) {
    ThreadPool.QueueUserWorkItem(state => { 
    task(state); 
    if (0 == Interlocked.Decrement(ref running))
      done.Set ();
    });
}
done.WaitOne();

With C# 4.0 you can use the new CountdownEvent primitive.