Join on the ThreadPool: is it possible?

  • Thread starter Thread starter Monsur
  • Start date Start date
M

Monsur

Hi there. I'm new to multithreaded programming. The way I understand it,
its not possible to Join() on threads spawned to the ThreadPool. However,
I'm in a situation where I'd like to be sure that all threads in the
threadpool have completed before moving to the next step. What's the
recommended pattern to implement this? Here's an example of what I'm trying
to do:

public static void Run(int iterations)
{
// iterate, while calling out to the threadpool
for (int i = 0; i < iterations; i++)
{
// ThreadArgs is just some wrapper class I created
ThreadArgs args = new ThreadArgs();
args.Iteration = i;
ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomething),
args);
}

// wait for all threads in the threadpool to finish
// how to do this?
}

Thanks!
Monsur
 
Use a "worker" delegate
Call the BeginInvoke method on the delegate returning an asyncronous result.
Using the AsyncWaitHandle on the IAsynResult interface, create an array of wait handles and add to the array
Pass array of wait handles as argument to the WaitAll method on Threading.WaitHandle

Don't forget to use EndInvoke when complete.
 
Back
Top