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


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