In .NET, under which circumstances should I use GC.SuppressFinalize()
?
What advantage(s) does using this method give me?
This question is related to
c#
.net
garbage-collection
idisposable
suppressfinalize
Dispose(true);
GC.SuppressFinalize(this);
If object has finalizer, .net put a reference in finalization queue.
Since we have call Dispose(ture)
, it clear object, so we don't need finalization queue to do this job.
So call GC.SuppressFinalize(this)
remove reference in finalization queue.
SupressFinalize
tells the system that whatever work would have been done in the finalizer has already been done, so the finalizer doesn't need to be called. From the .NET docs:
Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.
In general, most any Dispose()
method should be able to call GC.SupressFinalize()
, because it should clean up everything that would be cleaned up in the finalizer.
SupressFinalize
is just something that provides an optimization that allows the system to not bother queuing the object to the finalizer thread. A properly written Dispose()
/finalizer should work properly with or without a call to GC.SupressFinalize()
.
If a class, or anything derived from it, might hold the last live reference to an object with a finalizer, then either GC.SuppressFinalize(this)
or GC.KeepAlive(this)
should be called on the object after any operation that might be adversely affected by that finalizer, thus ensuring that the finalizer won't run until after that operation is complete.
The cost of GC.KeepAlive()
and GC.SuppressFinalize(this)
are essentially the same in any class that doesn't have a finalizer, and classes that do have finalizers should generally call GC.SuppressFinalize(this)
, so using the latter function as the last step of Dispose()
may not always be necessary, but it won't be wrong.
That method must be called on the Dispose
method of objects that implements the IDisposable
, in this way the GC wouldn't call the finalizer another time if someones calls the Dispose
method.
Source: Stackoverflow.com