views:

128

answers:

3

I'm calling Thread.Join on a ThreadPool thread at the end of a service. The code executed in the thread ends about the same time as Thread.Join is called, but the Join takes 2 minutes to return. Why is it taking 2 minutes for Thread.Join to return.

The log:

(2009-10-08 14:22:09) Inf: ProcessRequests - Interrupted, exiting.
(2009-10-08 14:22:09) Dbg: ProcessingDriver.Stop - Waiting on thread to exit.
(2009-10-08 14:24:10) Dbg: ProcessingDriver.Stop - Thread joined.

The code:

WaitHandle.Set(); //Signal it's time to go home
LogManager.Logger.WriteLog(LOG_SOURCE, "Waiting on thread to exit.", LogType.Debug, 7);
ProcessingThread.Join(); //Wait for the thread to go home
LogManager.Logger.WriteLog(LOG_SOURCE, "Thread joined.", LogType.Debug, 7);
+14  A: 

You shouldn't call Thread.Join on a ThreadPool thread.

When you call Thread.Join, it is keeping your main thread alive. The threadpool doesn't (necessarily) shut down its threads until your program is terminating. In your case, you're lucking out, and it's deciding to shut down that thread after a couple of minutes of idle time - but this isn't guaranteed. If you grab the wrong threadpool thread, it could hang forever.

If you need to wait on a task you setup, use a ManualResetEvent instead to track its completion.

Reed Copsey
+5  A: 

Why are you joining on a ThreadPool thread? The thread doesn't belong to you and could be used by the runtime for other operations. You should only join on your own threads.

bobbymcr
Because I was using a ThreadPool thread for a core process.
C. Ross
+1  A: 

Not sure, but the idea of threads in the thread pool are that they do not get disposed but are rather reused. Joining a thread will stop blocking when the thread terminates..

flq