Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a use case for not using "this" when calling GC.SuppressFinalize(this)?

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?
}
like image 556
Bob Horn Avatar asked Apr 13 '13 20:04

Bob Horn


People also ask

Should I call SuppressFinalize?

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().

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.

What is the use of GC SuppressFinalize?

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.

Why is it preferred to not use finalize for clean up?

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.


1 Answers

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.

like image 133
G.Y Avatar answered Sep 21 '22 13:09

G.Y