.NET 中的线程池和 .IsBackground
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,您可以更改它们。但你不应该。
出于同样的原因,您不会重新油漆借来的汽车。对于其他线程属性(例如优先级和 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.
线程什么时候结束?你的方法什么时候结束?我非常怀疑情况确实如此。线程池的全部意义在于,一旦线程完成,它就会被放回到池中以供重用。现在您已经释放了一个线程,它又回到了线程池中,并且您的应用程序仍在运行,因为它是前台线程。没有办法让该线程返回来杀死它。
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.
用“它们的 IsBackground 属性初始化为 True,这与使用 Thread 类创建的线程不同”来结束这句话。
将其设置为 false 可能有点冒险。线程池线程被回收,我不太确定该属性是否会被重新初始化。它不是与物理操作系统线程关联的属性,它们没有 IsBackground 行为,它是由 CLR 围绕它放置的包装器添加的。所以可能是的。不过,没有理由去搞乱它。
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.