Do not dispose objects multiple times

TypeName

DoNotDisposeObjectsMultipleTimes

CheckId

CA2202

Category

Microsoft.Usage

Breaking Change

NonBreaking

Cause

A method implementation contains code paths that could cause multiple calls to System.IDisposable.Dispose or a Dispose equivalent (such as a Close() method on some types) on the same object.

Rule Description

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.

How to Fix Violations

To fix a violation of this rule, change the implementation so that regardless of the code path, Dispose is called only one time for the object.

When to Exclude Warnings

Do not exclude a warning from this rule. Even if Dispose for the object is known to be safely callable multiple times, the implementation might change in the future.

See Also

Reference

Implementing Finalize and Dispose to Clean Up Unmanaged Resources
System.IDisposable