Search This Blog

Loading...

Nov 1, 2011

Garbage Collection: How to implement Dispose Method in .Net


Sponsored Links:
In .Net programmer is not responsible to clean the memory from managed type. It is happened automatically by Garbage collector. However sometime it becomes programmer responsibility to clean memory from unmanaged resources.


In CSharp you can achieve this either via finalize method or Dispose method. Dispose method is always suggested.  It is good to use when you want to cleanup your resources. It is implemented from I Disposable interface. It is always advisable do not call Dispose because it dose nothing.

public class Class1 : iDisposable{
    private bool isDisposable = false;
    
    public Class1()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    ~Class1()
    {
        Dispose(false);
    }


    protected void Dispose(bool disposing)
    {
        if (disposing)
        {
            // Code to dispose the managed resources of the class
        }
        // Code to dispose the un-managed resources of the class

        isDisposable = true;
    }
   

    public void Dispose()
    {
        Dispose(true);
        //supressFinalize is used to  boost up the performance
        GC.SuppressFinalize(this);
    }
}

public interface iDisposable{
    void Dispose();
}

Follow by Email