是否应该对没有终结器的对象调用 GC.SuppressFinalize?
由于某种原因 FXCop 似乎认为 我应该调用 GC.SuppressFinalize在 Dispose 中,无论我是否有终结器。
我错过了什么吗? 是否有理由对未定义终结器的对象调用 GC.SuppressFinalize?
For some reason FXCop seems to think I should be calling GC.SuppressFinalize in Dispose, regardless of whether I have a finalizer or not.
Am I missing something? Is there a reason to call GC.SuppressFinalize on objects that have no finalizer defined?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不需要在 Dispose 中调用 GC.SuppressFinalize(this),除非:
Object
中的终结器,则该对象不会被视为需要终结,并且不会在 GC 时放入终结列表中我想说,假设您没有上述任何情况,您可以安全地忽略该消息。
There's no need to call
GC.SuppressFinalize(this)
in Dispose, unless:Object
, then the object is not considered to need finalizing and isn't put on the finalization list upon GCI would say, assuming you don't have any of the above cases, that you can safely ignore that message.
IL 中总是有一个终结器 - System.Object.Finalize() 存在于每个类中,因此如果您创建一个自定义类,它就会有一个您想要抑制的终结器。 话虽如此,并非所有对象都会放入终结队列中,因此,如果您实现自己的终结器,则从技术上讲,您只需要抑制终结。
如果您要实现
IDisposable
来包装非托管资源,则应包含一个终结器,并且应阻止其运行,因为理论上您在Dispose
被调用。There is always a finalizer in IL - System.Object.Finalize() exists in every class, so if you make a custom class, it has a finalizer you want to suppress. That being said, not all objects are put on the finalization queue, so you only techncially should need to suppress finalization if you implement your own finalizer.
If you're implementing
IDisposable
to wrap unmanaged resources, you should include a finalizer, and you should prevent this from running, since in theory you're doing the cleanup already whenDispose
is called.看起来 FxCop 只是检查 Dispose(),而不检查析构函数是否存在。
忽略它应该是安全的。
It looks like FxCop simply inspects the Dispose() and doesn't check for the presence of a destructor.
It should be safe to ignore.
所有对象都有一个终结方法,即使您没有使用 ac# 析构函数(实际上并不能保证由 GC 调用)实现该方法。 如果您已经实现了 IDisposable,那么最好抑制该调用,因为这意味着您已决定显式执行终结。
devx 文章
All objects have a finalizer method, even if you have not implemented one by using a c# destructor (which is not actually guaranteed to be called by the GC). It's just good practice to supress the call if you have implemented IDisposable because that means you have decided to perform the finalization explictly.
devx article
如果没有定义终结器,我认为没有必要调用 SuppressFinalize() 。 如果您想采取防御措施,那么拥有终结器和 Dispose() 会很好,这样您就不需要依赖客户端始终调用 Dispose()。 这样当他们忘记时你就不会泄漏资源。
I don't see any need to call SuppressFinalize() if there's no finalizer defined. If you want to be defensive then it can be good to have a finalizer as well as Dispose(), so you don't need to rely on clients to always call Dispose(). Then you won't leak resources when they forget.