.NET 中的线程池和 .IsBackground

发布于 2024-09-17 18:47:54 字数 272 浏览 4 评论 0原文

MSDN 以及许多其他来源都声称线程池中的工作线程始终是后台的。

“线程池线程是后台线程。” (MSDN)

“池线程始终是后台线程。” (C# 中的线程,Joseph Albahari)

我可以通过设置轻松使工作线程成为非后台

Thread.CurrentThread.IsBackground = false;

应用程序将等待线程完成。

这有什么问题吗?

MSDN, as well as many other sources, claim that worker threads in the thread pool are always background.

"Thread pool threads are background threads." (MSDN)

"Pooled threads are always background threads." (Threading in C#, Joseph Albahari)

I can easily make the worker thread non-background by setting

Thread.CurrentThread.IsBackground = false;

And the application will be waiting until the thread finishes.

What's wrong with that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

你是我的挚爱i 2024-09-24 18:47:54

是的,您可以更改它们。但你不应该

出于同样的原因,您不会重新油漆借来的汽车。对于其他线程属性(例如优先级和 MTA)也是如此。

如果您想要不同类型的线程,请创建您自己的线程。

Yes, you can change them. But you should not.

For the same reasons you don't repaint a borrowed car. Same for other thread properties like priority and MTA.

If you want a different kind of thread, create your own.

叹倦 2024-09-24 18:47:54

线程什么时候结束?你的方法什么时候结束?我非常怀疑情况确实如此。线程池的全部意义在于,一旦线程完成,它就会被放回到池中以供重用。现在您已经释放了一个线程,它又回到了线程池中,并且您的应用程序仍在运行,因为它是前台线程。没有办法让该线程返回来杀死它。

When does the thread finish? When your method ends? I highly doubt that's the case. The whole point of the thread pool is that once your thread is finished, it gets put back in the pool to be reused. Now you've let go of a thread, it's gone back into the thread pool and your application is still running because it's a foreground thread. There's no way to get that thread back out to kill it.

凝望流年 2024-09-24 18:47:54

线程池线程是后台线程

用“它们的 IsBackground 属性初始化为 True,这与使用 Thread 类创建的线程不同”来结束这句话。

将其设置为 false 可能有点冒险。线程池线程被回收,我不太确定该属性是否会被重新初始化。它不是与物理操作系统线程关联的属性,它们没有 IsBackground 行为,它是由 CLR 围绕它放置的包装器添加的。所以可能是的。不过,没有理由去搞乱它。

Thread pool threads are background threads

Finish that sentence with "they have their IsBackground property initialized to True, unlike threads created with the Thread class."

Setting it to false could be a bit risky. Threadpool threads are recycled, I'm not so sure that the property will be re-initialized. It is not a property associated with the physical operating system thread, they don't have IsBackground behavior, it is added by the wrapper that the CLR puts around it. So probably yes. Little reason to mess with it though.

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