Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling SuppressFinalize multiple times

Is there any downside of calling GC.SuppressFinalize(object) multiple times?
Protected Dispose(bool) method of the dispose pattern checks whether it is called before but there is no such check in the public Dispose() method.

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
    if (_Disposed)
        return;

    if (disposing)
    {
        // Cleanup managed resources.
    }

    // Cleanup unmanaged resources.
    _Disposed = true;
}

~MyClass() { Dispose(false); }

Is it ok to call the Dispose() method of a MyClass instance multiple times?

like image 890
Şafak Gür Avatar asked Sep 15 '12 10:09

Şafak Gür


People also ask

Can you call dispose multiple times?

A correctly implemented Dispose method can be called multiple times without throwing an exception. However, this is not guaranteed and to avoid generating a System. ObjectDisposedException you should not call Dispose more than one time on an object.

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 does GC SuppressFinalize do?

GC. SuppressFinalize to prevent the garbage collector from implicitly invoking the finalizer a second time. Do not directly call your base class Finalize method. It is called automatically from your destructor.


1 Answers

According to docs: http://msdn.microsoft.com/en-us/library/system.gc.suppressfinalize.aspx, it sets some bit in object header, so there shouldn't be any implications of calling it multiple times.

like image 138
Bartosz Avatar answered Oct 03 '22 01:10

Bartosz