为什么 Thread.Join 需要这么长时间才能返回?
我在服务结束时在 ThreadPool 线程上调用 Thread.Join。线程中执行的代码大约在调用 Thread.Join 的同时结束,但 Join 需要 2 分钟才能返回。为什么 Thread.Join 需要 2 分钟才能返回。
日志:
(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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不应该在 ThreadPool 线程上调用 Thread.Join。
当您调用 Thread.Join 时,它会保持主线程处于活动状态。在程序终止之前,线程池不会(必然)关闭其线程。就您而言,您很幸运,并且它决定在几分钟的空闲时间后关闭该线程 - 但这并不能保证。如果你抓住了错误的线程池线程,它可能会永远挂起。
如果您需要等待设置的任务,请使用 ManualResetEvent 而是跟踪其完成情况。
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.
为什么要加入 ThreadPool 线程?该线程不属于您,运行时可以将其用于其他操作。您应该只加入您自己的线程。
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.
不确定,但线程池中线程的想法是它们不会被释放而是被重用。当线程终止时,加入线程将停止阻塞。
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..