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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With