为什么 Thread.Join 需要这么长时间才能返回?

发布于 2024-08-07 08:03:46 字数 681 浏览 5 评论 0原文

我在服务结束时在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

顾北清歌寒 2024-08-14 08:03:46

您不应该在 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.

╭ゆ眷念 2024-08-14 08:03:46

为什么要加入 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.

青朷 2024-08-14 08:03:46

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文