问题描述
基于文档(MSDN:链接),很明显,在实现终结器时应该使用 IDisposable 模式.
Based on the documentation (MSDN: link), it is clear that one should use the IDisposable pattern when implementing a finalizer.
但是,如果您实现了 IDisposable(以便提供一种确定性的对象处置方式),并且您没有任何非托管资源需要清理,您是否需要实现终结器?
But do you need to implement a finalizer if you implement IDisposable (so as to provide a deterministic way of disposing the object), and you dont have any unmanaged resources to clean up?
在我看来,如果该类只有托管资源并且您不调用 Dispose,则托管资源将自动被 GC 清理,因此无需实现终结器.我错了吗?
As I see it, if the class has only managed resources and if you dont call Dispose, the managed resources will automatically get cleaned up by the GC and hence no need to implement the finalizer. Am I wrong?
另外,如果我使用我的 Dispose 方法来清理事件处理程序会怎样.由于 Dispose 不会自动被 GC 调用,我是否应该实现一个终结器,以确保事件处理程序不连线?
Also, what if I am using my Dispose method to clean up event handlers. As Dispose wont automatically get called by the GC, should I implement a Finalizer, to ensure that eventhandlers get unwired?
推荐答案
不,如果你有一个实现 IDisposable 的类,你不需要实现终结器(也就是说,如果你已经正确实现了模式,并且你只已管理的资源进行处置).
No, you do not need to implement a finalizer if you have a class that implements IDisposable (that is if you have implemented the pattern correctly, and that you only have managed resources to dispose of).
(如果这样做,它实际上会影响对象的生命周期,因为带有终结器的对象会被添加到 GC 中的终结队列中,并且可以比它们需要的寿命更长 - 如果你的对象很大.)
这篇关于终结器和 IDisposable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)