I was just implementing the Dispose pattern, and when I just typed the GC.SuppressFinalize(this)
line, I was wondering if there is ever a use case for using something other than this
as the parameter to the method.
This is the typical pattern:
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this); // right here
}
Does it ever make sense to call GC.SuppressFinalize()
with something other than this
?
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(foo); // should this ever happen?
}
You should always call SuppressFinalize() because you might have (or have in the future) a derived class that implements a Finalizer - in which case you need it. Let's say you have a base class that doesn't have a Finalizer - and you decided not to call SuppressFinalize().
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.
The GC. SuppressFinalize() system method is designed to prevent calling the finalizer on the specified object. If an object does not have a destructor, invoking SuppressFinalize on this object has no effect and JetBrains Rider flags such call as redundant. To learn more how the destructor works, see Object.
The preferred way is to implement IDisposable along with the dispose pattern. Finalizers are time-limited and the GC will terminate a finalizer if it blocks for too long - this is the primary reason to avoid it where possible. Dispose is just a method call and is not time-limited.
According to MSDN:
http://msdn.microsoft.com/en-us/library/system.gc.suppressfinalize.aspx
It is in fact possible that your example: GC.SuppressFinalize(foo) will be used in certain scenarios, but not in the scenario of the common dispose pattern.
In example you might want to write some kind of dispose management pattern for many objects instead of implementing the common dispose pattern from within your object. another option is if you want an object to remain suppressed and later on maybe claim it? never done that.. but it's possible.
So possible yes.. likely to happen no - and probably never.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With