为什么Thread不实现IDisposable?

发布于 2024-08-11 05:45:32 字数 395 浏览 4 评论 0原文

我注意到 System.Threading.Thread 实现了终结器,但没有实现 IDisposable。推荐的做法是在实现终结器时始终实现 IDisposable。 Jeffrey Richter 写道 该指南“非常重要,应始终遵循”无一例外”。

那么Thread为什么不实现IDisposable呢?看起来实现 IDisposable 将是一个非破坏性的更改,它将允许确定性地清理 Thread 的可终结资源。

还有一个相关的问题:由于线程是可终结的,我是否必须保留对正在运行的线程的引用以防止它们在执行期间被终结?

I noticed that System.Threading.Thread implements a finalizer but not IDisposable. The recommended practice is to always implement IDisposable when a finalizer is implemented. Jeffrey Richter wrote that the guideline is "very important and should always be followed without exception".

So why doesn't Thread implement IDisposable? It seem like implementing IDisposable would be a non-breaking change that would allow deterministic cleanup of Thread's finalizable resources.

And a related question: since thread is finalizable, do I have to hold references to running Threads to prevent them from being finalized during execution?

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

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

发布评论

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

评论(3

清欢 2024-08-18 05:45:32

处置Thread对象会做什么?在这种情况下,“资源”有其自身的自然清理功能 - 线程整理。请注意,所有权意识也缺失......在执行线程中,您始终可以使用 Thread.CurrentThread ,因此只有该线程才能真正声明任何类型的所有权。

基本上我认为 Thread 是一个稍微不寻常的情况 - 底层资源有一个生命周期,但它不应该被显式清理。

What would disposing of a Thread object do? The "resource" in this case has its own natural clean-up - the thread finishing. Note that also the sense of ownership is missing... within the executing thread, you can always use Thread.CurrentThread, so only that thread would really able to claim any sort of ownership.

Basically I think Thread is a slightly unusual case - there's a lifetime to the underlying resource, but it isn't something that ought to be cleaned up explicitly.

冰魂雪魄 2024-08-18 05:45:32

这可能是因为您无法处置线程。相反,您可以使用 Abort() 或类似命令让它终止。

That's probably because you can't dispose of a thread. Instead you can ask it to die using Abort() or alike.

说不完的你爱 2024-08-18 05:45:32

这是一个设计问题,因此任何没有参与构建 .NET 这方面的人都只能推测。话虽如此,这篇博文提出了一个很好的观点:

...实现 IDisposable 不会有任何区别,至少在当前的 Thread 实现中是这样。我增加了创建的线程数量,并且句柄计数在某些时候会下降,因此有一些机制可以关闭它们

线程在自身之后会自然地进行清理,因此它们不是典型意义上需要管理的资源。

This is kind of a design question, so anyone who was not involved in building this aspect of .NET can only speculate. That being said, this blog post makes a good point:

...implementing IDisposable would not make any difference, at least in the current implementation of Thread. I increased the number of threads being created and the handle count goes down at some point so there is some mechanism for closing them

Threads do naturally clean up after themselves, so they are not a resource that needs to be managed in the typical sense.

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