I have the following code:
public void Dispose()
{
if (_instance != null)
{
_instance = null;
// Call GC.SupressFinalize to take this object off the finalization
// queue and prevent finalization code for this object from
// executing a second time.
GC.SuppressFinalize(this);
}
}
Although there is a comment that explains purpose of that GC-related call, I still don’t understand why it’s there.
Isn’t object destined for garbage collection once all instances cease from existence, like, when used in using block?
What’s the use case scenario where this would play important role?
When implementing the dispose pattern you might also add a finalizer to your class that calls
Dispose(). This is to make sure thatDispose()always gets called, even if a client forgets to call it.To prevent the dispose method from running twice (in case the object already has been disposed) you add
GC.SuppressFinalize(this);. The documentation provides a sample: