Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
TypeName |
DisposeMethodsShouldCallSuppressFinalize |
CheckId |
CA1816 |
Category |
Microsoft.Performance |
Breaking Change |
NonBreaking |
Cause
A type implements System.IDisposable.Dispose, has a finalizer, and Dispose does not call System.GC.SuppressFinalize(System.Object).
Rule Description
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.
How to Fix Violations
To fix a violation of this rule, add a call to SuppressFinalize to the Dispose method.
When to Exclude Warnings
Do not exclude a warning from this rule. Failure to suppress finalization degrades performance and provides no benefits.
Example
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);
}
}
}
Related Rules
Dispose methods should call base class dispose
Disposable types should declare finalizer
See Also
Reference
Implementing Finalize and Dispose to Clean Up Unmanaged Resources