应该“处置"仅用于包含非托管资源的类型?

Should quot;Disposequot; only be used for types containing unmanaged resources?(应该“处置仅用于包含非托管资源的类型?)
本文介绍了应该“处置"仅用于包含非托管资源的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近和一位同事讨论了 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 连接,那么实现 IDisposableusing 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)) {/*处理它*

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)