views:

48

answers:

2

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.

+3  A: 
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.

Remus Rusanu
Or the 4.0 Task class, better mousetrap.
Hans Passant
A: 

Joe Duffy wrote a great article on this sort of thing:

CLR Inside Out: 9 Reusable Parallel Data Structures and Algorithms

I'm eyballing the CountdownLatch as particularly appropriate for your requirements.

spender