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 连接,那么实现 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)) {/*处理它*
本文标题为:应该“处置"仅用于包含非托管资源的类型?


- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01