Skip to content

Gendarme.Rules.Performance.UseSuppressFinalizeOnIDisposableTypeWithFinalizerRule(2.10)

Sebastien Pouliot edited this page Feb 9, 2011 · 3 revisions

UseSuppressFinalizeOnIDisposableTypeWithFinalizerRule

Assembly: Gendarme.Rules.Performance
Version: 2.10

Description

This rule will fire if a type implements System.IDisposable and has a finalizer (called a destructor in C#), but the Dispose method does not call System.GC.SuppressFinalize. Failing to do this should not cause properly written code to fail, but it does place a non-trivial amount of extra pressure on the garbage collector and on the finalizer thread.

Examples

Bad example:

class BadClass : IDisposable {
    ~BadClass ()
    {
        Dispose (false);
    }
    public void Dispose ()
    {
        // GC.SuppressFinalize is missing so the finalizer will be called
        // which puts needless extra pressure on the garbage collector.
        Dispose (true);
    }
    private void Dispose (bool disposing)
    {
        if (ptr != IntPtr.Zero) {
            Free (ptr);
            ptr = IntPtr.Zero;
        }
    }
    [DllImport ("somelib")]
    private static extern void Free (IntPtr ptr);
    private IntPtr ptr;
}

Good example:

class GoodClass : IDisposable {
    ~GoodClass ()
    {
        Dispose (false);
    }
    public void Dispose ()
    {
        Dispose (true);
        GC.SuppressFinalize (this);
    }
    private void Dispose (bool disposing)
    {
        if (ptr != IntPtr.Zero) {
            Free (ptr);
            ptr = IntPtr.Zero;
        }
    }
    [DllImport ("somelib")]
    private static extern void Free (IntPtr ptr);
    private IntPtr ptr;
}

Notes

  • Prior to Gendarme 2.2 this rule was named IDisposableWithDestructorWithoutSuppressFinalizeRule
Clone this wiki locally