Friday, March 30, 2007

ThreadPool Join in C#

This post simply describes a way to use ThreadPool to parallelize e.g. an algorithm, and then wait for all workers to finish (i.e. 'join' all threads).

If you can spot anything that is incorrect, please comment!

Collection<ManualResetEvent> joinEvents = new Collection<ManualResetEvent>();
// Do all jobs, starting threads in a 
// controlled fashion via the ThreadPool
for (int i = 0; i < numJobs; i++)
{
ManualResetEvent workDone =
new ManualResetEvent(false);
joinEvents.Add(workDone);

ThreadPool.QueueUserWorkItem(delegate
{
// do stuff

workDone.Set();
});
}

// Wait for all threads to finish
// (or at least signal 'work done')
foreach (ManualResetEvent joinEvent in joinEvents)
{
joinEvent.WaitOne();
}

No comments: