C#: Dispose Pattern

In .NET, the Dispose Pattern...

  1. MUST be implemented if our class has references to unmanaged resources. For instance, references to C++/CLI objects which wrap native objects, native memory, etc.
  2. MUST be implemented if our class accesses limited resources, even if accessed through managed objects. For example, database connections.
  3. MUST be implemented if you wish to use RAII semantics for your class.
  4. SHOULD be implemented if your class contains big objects (a Dictionary with lots of keys, for example), and instances are created dynamically and relatively frequently. In this case, the objective is reclaiming memory as soon as possible, to avoid Out of Memory Scenarios due to memory fragmentation.

Once we decide to apply the pattern to a class, there are two possibilites. First, if the class is sealed AND it doesn't reference unmanaged resources, we can just override the Dispose Method::

public sealed class A : IDisposable{
    public void Dispose(){
        //Release managed resources and call Dispose for member variables
    }
}

If the class contains unmanaged resources, or it's not sealed, we must apply the pattern's most general form:

public class B : IDisposable{    
    public void Dispose(){
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing){
        if (disposing){
            //Release managed resources and call Dispose for member variables
        }   
        //Release unmanaged resources
    }

    ~B(){
        Dispose(false);
    }
}

Comments

Popular posts from this blog

VB.NET: Raise base class events from a derived class

Apache Kafka - I - High level architecture and concepts

Upgrading Lodash from 3.x to 4.x