2009-10-08 150 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

不確定,但線程池中線程的想法是,它們不會被丟棄,而是被重用。加入線程將在線程終止時停止阻塞。

相關問題