System.IDisposable Interface

Assembly

Library

Summary

Implemented by classes that require explicit control over resource cleanup.

Description

Objects that need to free resources that cannot safely be reclaimed by the
garbage collector implement the IDisposable interface.

It is a version breaking change to add the IDisposable interface to an existing class, as it
changes the semantics of the class.

[Note: IDisposable contains the System.IDisposable.Dispose method. The consumer of an object should
call this method when the object is no longer needed. The IDisposable interface is generally provided for the
release of unmanaged resources that need to be reclaimed in some order or time
dependent manner. It is important to note that the actual release of these
resources happens at the first call to System.IDisposable.Dispose for
any given object that supports this interface. Programmers should take care
to pair the creation of objects that implement IDisposable
with
at most one invocation of the Dispose
method. Though it
is legal to invoke Dispose
more than once, if this happens it
might indicate the presence of a bug since such an object is usually rendered
otherwise unusable after the first Dispose
invocation. ]

If an object's System.IDisposable.Dispose method is called more than once, the object should
ignore all calls after the first one. The object should not throw an exception
if its System.IDisposable.Dispose
method is called multiple times. System.IDisposable.Dispose can throw an exception if an error
occurs because a resource has already been freed and
System.IDisposable.Dispose had
not been called previously.

A resource type might use a particular convention to denote an allocated state
versus a freed state. An example of this is stream classes, which are
traditionally thought of as open or closed. Classes that have such conventions
might choose to implement a public method with a customized name, which calls the
System.IDisposable.Dispose
method.

Because the System.IDisposable.Dispose method must be called explicitly, objects that implement
IDisposable
should also implement a finalizer to handle freeing resources when
System.IDisposable.Dispose is not
called. By default, the garbage collector will automatically call an object's
finalizer prior to reclaiming its memory. However, once the
System.IDisposable.Dispose method
has been called, it is typically unnecessary and/or undesirable for the garbage
collector to call the disposed object's finalizer. To prevent automatic
finalization, System.IDisposable.Dispose implementations can call System.GC.SuppressFinalize(System.Object). For
additional information on implementing finalizers, see GC and System.Object.Finalize.

]

Example

Resource classes should follow the pattern illustrated by
this example: