0

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);
0

3 Answers 3

14

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.

5

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.

0
1

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..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.