问题描述
基于文档(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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!