Calling SuppressFinalize multiple times
Asked Answered
M

1

7

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?

Margotmargrave answered 15/9, 2012 at 10:24 Comment(2)
Don't bother GC unless you don't have another choice.Vanya
I want to make one thing clear: You only need a finalizer if you need to dispose of unmanaged resources (or if you run whacky caching schemes relying on finalization).Retroflex
G
9

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.

Gouache answered 15/9, 2012 at 10:37 Comment(1)
"If obj does not have a finalizer or the GC has already signaled the finalizer thread to run the finalizer, the call to the SuppressFinalize method has no effect."Kappenne

© 2022 - 2024 — McMap. All rights reserved.