Waiting for ThreadPool

  • Thread starter Thread starter Michael D. Ober
  • Start date Start date
M

Michael D. Ober

If I use standard Threading.Thread threads, I can issue a Join on the thread
variable and wait for it to complete. How can I do this on the Background
Worker Threads in a threadpool without looping. Basically, I will be
queuing an unknown number of worker threads in the pool and I need to wait
for them all to complete.

Thanks,
Mike Ober.
 
Michael D. Ober said:
If I use standard Threading.Thread threads, I can issue a Join on the
thread
variable and wait for it to complete. How can I do this on the Background
Worker Threads in a threadpool without looping. Basically, I will be
queuing an unknown number of worker threads in the pool and I need to wait
for them all to complete.

Pool threads never exit or they wouldn't be in the pool. Consequently you
cannot Join with them.

See WaitHandle.WaitAll

NB. It is crucial when using pool threads that you don't throw an exception
out of your delegate without signalling that it has exited (unlike Join
where you will get to know) therefore the delegate should ALWAYS be a
try...catch...finally block.

Ideally you use some sort of shared object to store the completion state,
initialize it to "software messed up" at the top of the try block, set it to
"success" at the bottom, set it to sepcific errors in the catch and signal
completion in the finally block.
 
Thanks.

Mike.

Nick Hounsome said:
Pool threads never exit or they wouldn't be in the pool. Consequently you
cannot Join with them.

See WaitHandle.WaitAll

NB. It is crucial when using pool threads that you don't throw an exception
out of your delegate without signalling that it has exited (unlike Join
where you will get to know) therefore the delegate should ALWAYS be a
try...catch...finally block.

Ideally you use some sort of shared object to store the completion state,
initialize it to "software messed up" at the top of the try block, set it to
"success" at the bottom, set it to sepcific errors in the catch and signal
completion in the finally block.
 
In the delegate, increment an int before exit. The last delegate out closes
the door - or in this case, it does a Set(). You other thread is waiting on
event.WaitOne() similar to a Join. So one event should handle it.

try
{
// run delegate code.
}
finally
{
int c = Interlocked.Increment(ref count);
if ( c >= numToWait) // Last one out?
autoEvent.Set();
}

--
William Stacey [MVP]

| If I use standard Threading.Thread threads, I can issue a Join on the
thread
| variable and wait for it to complete. How can I do this on the Background
| Worker Threads in a threadpool without looping. Basically, I will be
| queuing an unknown number of worker threads in the pool and I need to wait
| for them all to complete.
|
| Thanks,
| Mike Ober.
|
|
|
 
Back
Top