Dispose vs Finalize and Disposable Pattern

 Difference between Dispose and Finalize ?


Dispose
Finalize
It is used to free unmanaged resources like files, database connections etc. at any time.
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.

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

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

It belongs to IDisposable interface.

It belongs to Object class.

It's implemented by implementing IDisposable interface Dispose() method.

It's implemented with the help of destructor in C++ & C#.

There is no performance costs associated with Dispose method.

There is performance costs associated with Finalize method since it doesn't clean the memory immediately and called by GC automatically.

 

 Note : Source  (https://www.dotnettricks.com)
  • It is always recommended to use Dispose method to clean unmanaged resources. You should not implement the Finalize method until it is extremely necessary.
  • At runtime C#, C++ destructors are automatically Converted to Finalize method. But in VB.NET you need to override Finalize method, since it does not support destructor.
  • 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.
When to use IDisposable ?

 This answer I like it from Stack Overflow .

  • You should never implement IDisposable in a class unless you need it. To be very specific, there are about 5 times when you would ever need/should implement IDisposable:
  • Your class explicitly contains (i.e. not via inheritance) any managed resources which implement IDisposable and should be cleaned up once your class is no longer used. For example, if your class contains an instance of a Stream, DbCommand, DataTable, etc.
  • Your class explicitly contains any managed resources which implement a Close() method - e.g. IDataReader, IDbConnection, etc. Note that some of these classes do implement IDisposable by having Dispose() as well as a Close() method.
  • Your class explicitly contains an unmanaged resource - e.g. a COM object, pointers (yes, you can use pointers in managed C# but they must be declared in 'unsafe' blocks, etc. In the case of unmanaged resources, you should also make sure to call System.Runtime.InteropServices.Marshal.ReleaseComObject() on the RCW. Even though the RCW is, in theory, a managed wrapper, there is still reference counting going on under the covers.
  • If your class subscribes to events using strong references. You need to unregister/detach yourself from the events. Always to make sure these are not null first before trying to unregister/detach them!.

How to use Finalizer ? (Source MSDN)

Your class contains any combination of the above.
  • Finalizers cannot be defined in structs. They are only used with classes.
  • A class can only have one finalizer.
  • Finalizers cannot be inherited or overloaded.
  • Finalizers cannot be called. They are invoked automatically. 
  • A finalizer does not take modifiers or have parameters.

 


The finalizer implicitly calls Finalize on the base class of the object. Therefore, a call to a finalizer is implicitly translated to the following code:

protected override void Finalize()
{
            try
            {
                // Cleanup statements... 
            }
            finally
            {
                base.Finalize();
            }
}

Since we don't have control over calling this method which calls recursively until it's base class is reached and call should go to finalize queue which leads to performance issues , it is better to handle the cleanup operations using dispose method.

No comments:

Post a Comment

Pages