Join on the ThreadPool: is it possible?

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
 
G

Guest

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top