Why the disposable design pattern?
The dispose pattern is used only for objects that access unmanaged resources, such as file and pipe handles, registry handles, wait handles or pointers to blocks of unmanaged memory. Implementation of IDisposable provides both implicit & explicit way to free resources from memory.
This is because the garbage collector is very efficient at reclaiming unused managed objects, but it is unable to reclaim unmanaged objects.
- DO implement the basic dispose pattern on types containing instances of disposable types.
- Even when you provide explicit control using Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose.
- If I am creating a new class how do I decide that it should implement IDisposible?
- If it is using unmanaged resources then you should implement IDisposable interface on that class.
- If any of the members or fields are implementing IDisposable interface your class should implement IDisposable.
- If the base type has a Close method, often this indicates the need to implement Dispose.
- After Dispose has been called on an instance, prevent the Finalize method from running by calling the GC.SuppressFinalize.