public interface IDisposable
|
Use the IDisposable.Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.
It is a version breaking change to add the IDisposable interface to an existing class, as it changes the semantics of the class.
For a detailed discussion about how this interface and the Object.Finalize method are used, see the the conceptual topic at MSDN: programmingessentialsforgarbagecollection and the conceptual topic at MSDN: implementingdisposemethod topics.
Dispose | Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. |
void Dispose(); |
When implementing this method, objects must seek to ensure that all held resources are freed by propagating the call through the containment hierarchy. For example, if an object A allocates an object B, and object B allocates an object C, then A's IDisposable.Dispose implementation must call IDisposable.Dispose on B, which must in turn call IDisposable.Dispose on C. Objects must also call the IDisposable.Dispose method of their base class if the base class implements IDisposable.
If an object's IDisposable.Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its IDisposable.Dispose method is called multiple times. IDisposable.Dispose can throw an exception if an error occurs because a resource has already been freed and 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, such as Close, which calls the IDisposable.Dispose method.
Because the IDisposable.Dispose method must be called explicitly, objects that implement IDisposable must also implement a finalizer to handle freeing resources when 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 IDisposable.Dispose method has been called, it is typically unnecessary for the garbage collector to call the disposed object's finalizer. To prevent automatic finalization, IDisposable.Dispose implementations can call the GC.SuppressFinalize method.
For more information on implementing finalizers, see the GC class and the Object.Finalize method.