问题描述
当我会实现IDispose一类,而不是析构函数?我读这篇文章,但我仍然缺少点。
When would I implement IDispose on a class as opposed to a destructor? I read this article, but I'm still missing the point.
我的假设是,如果我实现IDispose一个对象,我可以明确地'毁灭'它,而不是等待垃圾回收器来做到这一点。这是正确的?
My assumption is that if I implement IDispose on an object, I can explicitly 'destruct' it as opposed to waiting for the garbage collector to do it. Is this correct?
这是否意味着我应该始终明确地调用Dispose的对象?这有什么一些常见的例子?
Does that mean I should always explicitly call Dispose on an object? What are some common examples of this?
推荐答案
一个终结器(又名析构函数)是垃圾回收(GC)的一部分 - 它是不确定的时候(或者即使)出现这种情况,因为GC主要发生作为内存pressure结果(即需要更多的空间)。终结通常仅用于清理的非托管的资源,因为管理资源将有自己的集合/处置。
A finalizer (aka destructor) is part of garbage collection (GC) - it is indeterminate when (or even if) this happens, as GC mainly happens as a result of memory pressure (i.e. need more space). Finalizers are usually only used for cleaning up unmanaged resources, since managed resources will have their own collection/disposal.
因此的IDisposable
现在用于的确定性的清理对象,即。它不收集对象的内存(即仍属于GC) - 但用于例如关闭文件,数据库连接,等等
Hence IDisposable
is used to deterministically clean up objects, i.e. now. It doesn't collect the object's memory (that still belongs to GC) - but is used for example to close files, database connections, etc.
有很多previous主题上这样的:
There are lots of previous topics on this:
- deterministic定稿
- 处理对象
- using阻止
- resources
- deterministic finalization
- disposing objects
- using block
- resources
最后,请注意,这并非罕见的的IDisposable
对象也有一个终结;在这种情况下,的Dispose()
呼叫通常 GC.Sup pressFinalize(本)
,这意味着GC没有按'T运行的终结 - 它只是抛出内存远(更便宜)。终结还是你忘了运行的Dispose()
的对象。
Finally, note that it is not uncommon for an IDisposable
object to also have a finalizer; in this case, Dispose()
usually calls GC.SuppressFinalize(this)
, meaning that GC doesn't run the finalizer - it simply throws the memory away (much cheaper). The finalizer still runs if you forget to Dispose()
the object.
这篇关于使用IDisposable的VS在C#中的析构函数之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!