Wednesday, 10 February 2016

How to implement Dispose Method? Differences between Dispose and Finalize methods ?



It is always recommended to use Dispose method to clean unmanaged resources. You should not implement the Finalize method until it is extremely necessar

You should not implement a Finalize method for managed objects, because the garbage collector cleans up managed resources automatically.

A Dispose method should call the GC.SuppressFinalize() method for the object of a class which has destructor because it has already done the work to clean up the object, then it is not necessary for the garbage collector to call the object's Finalize method.

Code Example:-

public class MyClass : IDisposable
    {
        private bool disposed = false;
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        //Implement Dispose method to dispose resources
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    // TO DO: clean up managed objects
                    Console.WriteLine("Managed code has been disposing");
                    Console.ReadKey();
                }

                // TO DO: clean up unmanaged objects
                Console.WriteLine("UnManaged code has been disposing");
                Console.ReadKey();
                disposed = true;
            }
        }
    }
    class Program
    {
        public static void Main(String[] agues)
        {
            MyClass mc = new MyClass();
            mc.Dispose();
            Console.WriteLine("All resources are released from memory.");
            Console.ReadKey();
        }
         
    }



 Output:-


  



Dispose() Method:-

  • It is used to free unmanaged resources like files, database connections etc. at any time.
  • Explicitly, it is called by user code and the class which is implementing dispose method, must has to implement IDisposable interface.
  • It belongs to IDisposable interface.
  • It's implemented by implementing IDisposable interface Dispose() method.
  • There is no performance costs associated with Dispose method.

Finalize() Method:-

  • It can be used to free unmanaged resources (when you implement it) like files, database connections etc. held by an object before that object is destroyed.
  • Internally, it is called by Garbage Collector and cannot be called by user code.
  • It belongs to Object class.
  • It's implemented with the help of destructor in C++ & C#.
  • There is performance costs associated with Finalize method since it doesn't clean the memory immediately and called by GC automatically.





No comments:

Post a Comment