Export (0) Print
Expand All

Dispose methods should call SuppressFinalize

TypeName

DisposeMethodsShouldCallSuppressFinalize

CheckId

CA1816

Category

Microsoft.Performance

Breaking Change

NonBreaking

A type implements System.IDisposable.Dispose, has a finalizer, and Dispose does not call System.GC.SuppressFinalize(System.Object).

The Dispose method lets users release resources at any time prior to the object becoming available for garbage collection. If the Dispose method is called, it frees the resources of the object, making finalization unnecessary. Dispose should call SuppressFinalize so the garbage collector does not call the finalizer of the object.

To fix a violation of this rule, add a call to SuppressFinalize to the Dispose method.

Do not exclude a warning from this rule. Failure to suppress finalization degrades performance and provides no benefits.

The following example shows a method that satisfies this rule.

using System;  

namespace PerformanceLibrary
{
    public class  TypeA :IDisposable
    {
        // Assume this type has some unmanaged resources.
        private bool disposed = false;

        protected virtual void Dispose(bool disposing) 
        {
            if (!disposed) 
            {
                // Dispose of resources held by this instance.
                // (This process is not shown here.)

                // Set the sentinel.
                disposed = true;
   
                // Suppress finalization of this disposed instance.
                if (disposing)
                {
                    GC.SuppressFinalize(this);
                }
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }

        // Disposable types implement a finalizer.
        ~TypeA()
        {
            Dispose(false);
        }
    }
}

Community Additions

ADD
Show:
© 2014 Microsoft