Why Dispose() is preferred than Finalize() for Un-Managed Resources in .NET?

Memory management is very important in any application development.The Garbage collector of .NET does almost all clean up activity for your objects.For unmanaged resources (Ex:Windows API created objects, File, Database connection objects, COM objects, etc.) are outside the scope of .NET framework.

Why Dispose() is preferred than Finalize()


If we use the "Finalize()" method,the 
Garbage collector has to make two round in order to remove the objects.

For an instance ,let me explain clearly if we have two objects as Object1 and Object2 and we finalize the Object2 as given in the below image.The GC has to categorize the two objects and put the Finalize objects into Finalization Queue.The GC will clean the object1 which doesn't use the Finalize() method and process the second round of cleaning the Finalization Queue.



Finalize() method Process
Now at this the "Dispose()" method will come into picture.This method belongs to IDisposable() interface .So the best practise to release the unmanaged code,implement IDisposable() and override the Dispose() method.If we write any re-usable component for client we need to expose the Dispose method so that client can use that method.In a worst scenario if the client forgets to call this method ,then How do we force the Dispose method to be called automatically?

Implement as given below 
public class CleanClass : IDisposable
    {
        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }
        protected override void Finalize()
        {
            Dispose();
        }
    }

Popular posts from this blog

Exporting to excel from a custom class object using C#.NET

Get the Clicked Cell Value and Column Name of GridView in ASP.NET

How to apply watermark to the textbox and dropdownlist?