为什么Thread不实现IDisposable?
我注意到 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
处置
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 useThread.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.这可能是因为您无法处置线程。相反,您可以使用
Abort()
或类似命令让它终止。That's probably because you can't dispose of a thread. Instead you can ask it to die using
Abort()
or alike.这是一个设计问题,因此任何没有参与构建 .NET 这方面的人都只能推测。话虽如此,这篇博文提出了一个很好的观点:
线程在自身之后会自然地进行清理,因此它们不是典型意义上需要管理的资源。
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:
Threads do naturally clean up after themselves, so they are not a resource that needs to be managed in the typical sense.