2009-10-08 185 views
0

我在服务末尾的ThreadPool线程上调用Thread.Join。线程中执行的代码与Thread.Join被调用的时间大致相同,但Join需要2分钟才能返回。为什么Thread.Join需要2分钟才能返回。为什么Thread.Join需要很长时间才能返回?

日志:

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

代码:

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

你不应该叫的Thread.join一个线程池线程。

当你调用Thread.Join时,它保持你的主线程活着。线程池不会(必然)关闭其线程,直到程序终止。在你的情况下,你正在偷懒,并且在几分钟的闲置时间后决定关闭该线程 - 但这并不能保证。如果你抓住错误的线程池线程,它可能永远挂起。

如果您需要等待您设置的任务,请改用ManualResetEvent来追踪其完成。

5

你为什么加入ThreadPool线程?该线程不属于您,可以被运行时用于其他操作。你应该只加入你自己的线程。

+0

因为我为一个核心进程使用了​​ThreadPool线程。 – 2009-10-08 18:54:32

1

不确定,但线程池中线程的想法是,它们不会被丢弃,而是被重用。加入线程将在线程终止时停止阻塞。

相关问题