Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should GC.SuppressFinalize be called on objects that do not have a finalizer?

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?

like image 841
Sam Saffron Avatar asked Mar 07 '09 02:03

Sam Saffron


People also ask

Why should one call GC SuppressFinalize when implementing Dispose method?

Dispose should call GC. SuppressFinalize so the garbage collector doesn't call the finalizer of the object. To prevent derived types with finalizers from having to reimplement IDisposable and to call it, unsealed types without finalizers should still call GC.

Which of the following method notifies garbage collector not to call finalize?

Finalize method, is used to release unmanaged resources before an object is garbage-collected. If obj does not have a finalizer or the GC has already signaled the finalizer thread to run the finalizer, the call to the SuppressFinalize method has no effect.

When would you use a finalizer?

Finalizers (historically referred to as destructors) are used to perform any necessary final clean-up when a class instance is being collected by the garbage collector. In most cases, you can avoid writing a finalizer by using the System. Runtime.

What does GC SuppressFinalize do?

SuppressFinalize tells the GC that the object was cleaned up properly and doesn't need to go onto the finalizer queue. It looks like a C++ destructor, but doesn't act anything like one. The SuppressFinalize optimization is not trivial, as your objects can live a long time waiting on the finalizer queue.


1 Answers

There's no need to call GC.SuppressFinalize(this) in Dispose, unless:

  • You are the base class that implements virtual Dispose methods intended for overriding (again, it might not be your responsibility even here, but you might want to do it in that case)
  • You have a finalizer yourself. Technically, every class in .NET has a finalizer, but if the only finalizer present is the one in Object, then the object is not considered to need finalizing and isn't put on the finalization list upon GC

I would say, assuming you don't have any of the above cases, that you can safely ignore that message.

like image 66
Lasse V. Karlsen Avatar answered Sep 21 '22 17:09

Lasse V. Karlsen