[英]Why doesn't Thread implement IDisposable?
I noticed that System.Threading.Thread implements a finalizer but not IDisposable. 我注意到System.Threading.Thread实现了终结器而不是IDisposable。 The recommended practice is to always implement IDisposable when a finalizer is implemented. 建议的做法是在实现终结器时始终实现IDisposable。 Jeffrey Richter wrote that the guideline is "very important and should always be followed without exception". 杰弗里里希特写道 ,该指南“非常重要,应始终遵循”。
So why doesn't Thread implement IDisposable? 那么为什么Thread没有实现IDisposable? It seem like implementing IDisposable would be a non-breaking change that would allow deterministic cleanup of Thread's finalizable resources. 看起来实现IDisposable似乎是一个非破坏性的变化,可以确定性地清理Thread的可终结资源。
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? 还有一个相关的问题:由于线程是可终结的,我是否必须保持对运行Threads的引用以防止它们在执行期间被最终确定?
What would disposing of a Thread
object do? 什么会处置一个Thread
对象呢? 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. 请注意,缺少所有权感......在执行线程中,您始终可以使用Thread.CurrentThread
,因此只有该线程才能真正声明任何类型的所有权。
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. 基本上我认为Thread
是一个稍微不寻常的情况 - 底层资源有一个生命周期,但它不是应该明确清理的东西。
That's probably because you can't dispose of a thread. 这可能是因为你不能处理一个线程。 Instead you can ask it to die using Abort()
or alike. 相反,你可以使用Abort()
或类似的方式让它死亡。
This is kind of a design question, so anyone who was not involved in building this aspect of .NET can only speculate. 这是一个设计问题,所以任何不参与构建.NET这方面的人都只能推测。 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. ...实现IDisposable不会有任何区别,至少在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. 线程自然会自然清理,因此它们不是需要在典型意义上进行管理的资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.