Monday, 18 August 2014

Dispose and Finalize



Difference between Dispose and Finalize

Finalize
Dispose

Finalize means destructor 


Dispose() is method in IDisposable interface

Every class has Finalize or destructor by default


For Dispose method you must have implemented IDisposable interface



Internally, it is called by Garbage Collector and cannot be called by user code.


Explicitly, it is called by user code and the class implementing dispose method must implement IDisposable interface.


You cannot suppress dispose from Finalize method


You can suppress Finalize method from dispose using SupreeFinalize method


Decreases the memory performance


Increases the memory performance

Implement it when you have unmanaged resources in your code, and want to make sure that these resources are freed when the Garbage collection happens.


Implement this when you are writing a custom class that will be used by other users.

class MyClass
{
    // constructor
    public MyClass()
    {
       // code
    }

    // destructor
    ~MyClass()
    {
       // code
    }
}




Dispose for Base class:


class BaseClass : IDisposable
{
   // Flag: Has Dispose already been called? 
   bool disposed = false;

   // Public implementation of Dispose pattern callable by consumers. 
   public void Dispose()
   {
      Dispose(true);
      GC.SuppressFinalize(this);          
   }

   // Protected implementation of Dispose pattern. 
   protected virtual void Dispose(bool disposing)
   {
      if (disposed)
         return;

      if (disposing) {
         // Free any other managed objects here. 
         //
      }

      // Free any unmanaged objects here. 
      //
      disposed = true;
   }
}


Dispose for Derived class:


class DerivedClass : BaseClass
{
   // Flag: Has Dispose already been called? 
   bool disposed = false;
 
   // Protected implementation of Dispose pattern. 
   protected override void Dispose(bool disposing)
   {
      if (disposed)
         return; 
 
      if (disposing) {
         // Free any other managed objects here. 
         //
      }
 
      // Free any unmanaged objects here. 
      //
      disposed = true;
      // Call base class implementation. 
      base.Dispose(disposing);
   }
}



  

No comments:

Post a Comment