.net 中的 Finalize 和 Dispose 有什么区别?
可能的重复:
完成与处置
大家好,
最近我在一次采访中被问到有关 Finalize 和 Dispose 的问题。它们分别何时使用以及垃圾收集器与它们有何关系。请分享链接以了解有关该主题的更多信息。
请分享...
提前致谢。
Possible Duplicate:
Finalize vs Dispose
Hi,
Recently I was quizzed in an interview about finalize and dispose. When is each one of them used and how is Garbage Collector related to them. Kindly share links to enlighten more on the topic.
Kindly share ...
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
垃圾回收在符合条件的对象之前运行终结器用于收集被回收。
Dispose()
用于清理非托管资源,例如网络连接、文件、操作系统内容的句柄等。它与using
块结合使用效果最佳,编译器确保在完成对象处理后立即调用Dispose()
– 并且还确保您不能一旦对象被处理掉,就可以不再使用该对象。请注意,终结器不必 run,所以依赖它可能是危险的:
还要注意对象符合收集条件的精确时间。阅读上面链接的文章 - 它既不是范围(一个奇怪的词,与对象的生命周期无关 - 它是 “合法的程序文本区域通过其非限定名称引用[命名实体]。”)也不是严格的引用计数,因为即使在对它的最后一个引用消失之前,对象也可以成为符合收集条件的对象。
Finalizers are run by the Garbage Collection before an object that is eligible for collection is reclaimed.
Dispose()
is meant for cleaning up unmanaged resources, like network connections, files, handles to OS stuff, &c. It works best in conjunction with theusing
block where the compiler makes sure thatDispose()
will be called immediately once you are done with an object – and also ensures that you cannot work with the object anymore once it's disposed.Note that finalizers don't have to run, so relying on that can be dangerous:
Careful also with the precise time when an object becomes eligible for collection. Read the article linked above – it's neither scope (a weird word which has noting to do with the lifetime of an object – it's “the region of program text in which it is legal to refer to [a named entity] by its unqualified name.”) nor is it strictly reference counting as an object can become eligible for collection even before the last reference to it goes away.
不确定性非确定性析构函数/终结器调用当不再有对此实例的引用时,垃圾收集器会自动执行此操作。undeterministicnondeterministic destructor/finalizer called automatically by the Garbage Collector when there are no more references to this instance.