我最近和一位同事讨论了 Dispose
的值和实现 IDisposable
的类型.
I was having a discussion with a colleague recently about the value of Dispose
and types that implement IDisposable
.
我认为为应该尽快清理的类型实现 IDisposable
是有价值的,即使没有要清理的非托管资源.
I think there is value in implementing IDisposable
for types that should clean up as soon as possible, even if there are no unmanaged resources to clean up.
我的同事想法不同;如果您没有任何非托管资源,则无需实施 IDisposable
,因为您的类型最终会被垃圾回收.
My colleague thinks differently; implementing IDisposable
if you don't have any unmanaged resources isn't necessary as your type will eventually be garbage collected.
我的论点是,如果您有一个想要尽快关闭的 ADO.NET 连接,那么实现 IDisposable
和 using new MyThingWithAConnection()
将使感觉.我的同事回答说,ADO.NET 连接实际上是一个非托管资源.我对他的回复是一切最终都是非托管资源.
My argument was that if you had an ADO.NET connection that you wanted to close as soon as possible, then implementing IDisposable
and using new MyThingWithAConnection()
would make sense. My colleage replied that, under the covers, an ADO.NET connection is a unmanaged resource. My reply to his reply was that everything ultimately is an unmanaged resource.
我知道推荐的一次性模式,其中如果调用了 Dispose
,则释放托管和非托管资源,但如果通过终结器/析构函数调用,则仅释放非托管资源(并在不久前发表了关于如何提醒消费者不当使用您的 IDisposable 类型)
I am aware of the recommended disposable pattern where you free managed and unmanaged resources if Dispose
is called but only free unmanaged resources if called via the finalizer/destructor (and blogged a while ago about how to alert consumers of improper use of your IDisposable types)
所以,我的问题是,如果你有一个不包含非托管资源的类型,是否值得实现 IDisposable
?
So, my question is, if you've got a type that doesn't contain unmanaged resources, is it worth implementing IDisposable
?
IDisposable
有不同的有效用途.一个简单的例子是持有一个打开的文件,当您不再需要它时,您需要在某个时刻将其关闭.当然,您可以提供一个方法 Close
,但将它放在 Dispose
中并使用像 这样的模式 using (var f = new MyFile(path)) {/*处理它*