Implementing Finalize and Dispose(.NET Framework) in C#

This article describes about implementing between dispose and finalize methods for cleaning up resources. It also tells you the difference between dispose and finalize methods.


Implementation of Finalize in C#

Finalize method is also called as destructor of class. It is ideal place to clean unmanaged resources implicitly like File Handlers, COM objects, Database connection that has referred by class. Finalize get called implicitly only once in lifetime of object and that is when object becomes out of scope.

Although the garbage collector knows the lifetime of object which uses unmanaged objects, it does not know how to clean and release unmanaged objects. Garbage Collector calls this method at some point after there are no longer any valid references to the object. In inheritance chain Finalize method is called from the most-derived to the least-derived means the top most base class Finalize get called at last.

Writing clean up code in the destructor or finalize leads to GC visit twice and thus affecting the performance multifold times. You can get more tips on ASP.NET performance tips. Writing finalize makes your class expensive even it never get called. So use it only when it is absolutely required to cleanup unmanaged code. Whenever you use Finalize method also implement IDisposable.Dispose with GC.SuppressFinalize.

When you use destructor to release resources it implicitly calls Finalize method of base class. A destructor and finalizer are basically interchangeable concepts.

For example, the below is a declaration of a destructor for class Customer:


class Customer
{
    ~Customer()  // destructor
    {
        // cleanup statements...
    }
}
    
    

The destructor of Customer class implicitly calls Finalize of base class of the object. Therefore, the previous destructor code is implicitly translated to below code


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

Implementation of Dispose method in C#

Cleaning up resources through Finalize or Destructor is non deterministic because GC has its own algorithm to reclaim memory. The CLR gives a way to implement deterministic cleaning of resources using IDisposable interface, Dispose method allow object to execute it explicitly.

The issue with non deterministic finalization is, it happens at undetermined point mostly when memory is not enough to work. So the objects like DB connection or File handlers are unnecessary alive in memory.

For cleaning up resources in deterministic way you have IDisposable.Dispose method. In each class when there is reference to any unmanaged resource you should give user ability to clean resource explicitly by providing Dispose method.


public class Customer : IDisposable
{
    private StringReader _reader;
       
    // to detect redundant calls
    private bool disposed = false; 

    public Customer()
    {
        this._reader = new StringReader();
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                if (reader != null) {
                    this._reader.Dispose();
                }
            }

            disposed = true;
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}
    
    

Difference Between Finalize and Dispose Method

Finalize Dispose

It is method of Object class.

It is implemented as part of IDisposable interface.

Finalize is responsible for cleaning of unmanaged resources like Files, DB connections, COM etc. held by object before that object is destroyed.

Dispose can release unmanaged resources like Files, DB connections, COM etc. at any time.

It is called by Garbage Collector and cannot be called by User.

It is users' responsibility to call Dispose method explicitly.

It has performance cost as GC has to visit Finalize twice.

No performance cost. Rather it helps to release resources as soon as possible.

Recommended it when you have unmanaged resources, and want to make sure about these resources to be freed when the Garbage collection happens.

Recommended it when your class users get facility to free resources.

Speak your mind :
Leave a comment for this article on dotnetbloogers.com