The IDisposable interface
Deterministic disposal of resources can be done by implementing the System.IDisposable
interface. This interface has a single method called Dispose()
that can be explicitly called by users when an object is no longer used and its resources can be disposed of. However, you should only implement this interface in the following circumstances:
- The class has ownership of unmanaged resources
- The class has ownership of managed resources that are themselves disposable
The way this interface should be implemented depends on whether the class has ownership of unmanaged resources. The general pattern, when you have both managed and unmanaged resources, is as follows:
public class MyResource : IDisposable { Â Â Â Â private bool disposed = false; Â Â Â Â protected virtual void Dispose(bool disposing) Â Â Â Â { Â Â Â Â Â Â Â Â if (!disposed) Â Â Â Â Â ...