Tag:

.net

    Difference Between Finalize and Dispose Method

    While working on real time projects, we normally create so many intefaces, clasess and using unmanged resources like DB connection, files operation etc. To manage performance of the application these resources should be freed on time. We can cleanup those resources using Dispose and Finalize methods.

    Class instances encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, we should provide both an explicit and an implicit way to free those resources.

    We should provide implicit control by implementing the protected Finalize on an object.The Finalize method is called when our object is garbage collected and we have no guarantee when this will happen (we can force it, but it will hurt performance).

    In some cases, we might want to release external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved by explicitly releases resources when they are no longer being used. To provide explicit control, we should implement the Dispose provided by the IDisposable.

    The standard practice is to implement IDisposable and Dispose so that we can use our object in a using statment. Such as using(var foo = new MyObject()) { }. And in your finalizer, you call Dispose, just in case the calling code forgot to dispose of you.

    Finalize Method

    • Finalizers should always be protected, not public or private so that the method cannot be called from the application’s code directly and at the same time, it can make a call to the base.Finalize method
    • Finalizers should release unmanaged resources only
    • The framework does not guarantee that a finalizer will execute at all on any given instance
    • Never allocate memory in finalizers or call virtual methods from finalizers
    • Avoid synchronization and raising unhandled exceptions in the finalizers
    • The execution order of finalizers is non-deterministic—in other words, you can’t rely on another object still being available within your finalizer
    • Do not define finalizers on value types
    • Don’t create empty destructors. In other words, you should never explicitly define a destructor unless your class needs to clean up unmanaged resources and if you do define one, it should do some work. If, later, you no longer need to clean up unmanaged resources in the destructor, remove it altogether.

    Dispose Method

    • Implement IDisposable on every type that has a finalizer
    • Ensure that an object is made unusable after making a call to the Dispose method. In other words, avoid using an object after the Dispose method has been called on it
    • Call Dispose on all IDisposable types once you are done with them
    • Allow Dispose to be called multiple times without raising errors
    • Suppress later calls to the finalizer from within the Dispose method using the GC.SuppressFinalize method
    • Avoid creating disposable value types
    • Avoid throwing exceptions from within Dispose methods

    Microsoft recommendation on Object Cleanup

    Microsoft recommends that you implement both Dispose and Finalize when working with unmanaged resources. The Finalize implementation would run and the resources would still be released when the object is garbage collected even if a developer neglected to call the Dispose method explicitly. Additionally call the Dispose method for any .NET objects that you have as components inside that class(having unmanaged resources as their member) from the Dispose method.

    Deciding Factor for Dispose/Finalized Method

    Destructor ~(it’s almost equal to base.Finalize()), The destructor is converted into an override version of the Finalize method that executes the destructor’s code and then calls the base class’s Finalize method. It is totally non deterministic and we can’t know when will be called because it depends on GC.

    • If a class contains no managed resources and no unmanaged resources, it doesn’t need to implement IDisposable or have a Finalize.
    • If the class has only managed resources, it should implement IDisposable but it doesn’t need a Finalize.
    • If the class has only unmanaged resources, it needs to implement IDisposable and needs a Finalize in case the program doesn’t call Dispose. The Dispose method must be safe to run more than once. You can achieve that by using a variable to keep track of whether it has been run before.
    • The Dispose method should free both managed and unmanaged resources.
    • The Finalize should free only unmanaged resources.
    • After freeing resources, the Dispose should call GC.SuppressFinalize, so the object can skip the finalization queue.

    An Example of a an implementation for a class with unmanaged and managed resources:

    using System;
    public class DisposableClass : IDisposable
    {
        // A name to keep track of the object.
        public string ProductName = "";
        // Free managed and unmanaged resources.
        public void Dispose()
        {
            FreeResources(true);
        }
        // Destructor to clean up unmanaged resources
        // but not managed resources.
        ~DisposableClass() // the finalizer
        {
            FreeResources(false);
        }
        // Keep track if whether resources are already freed.
        private bool IsResourcesFreed = false;
        // Free resources.
        private void FreeResources(bool freeManagedResources)
        {
            Console.WriteLine(ProductName + ": FreeResources");
            if (!ResourcesAreFreed)
            {
                // Dispose of managed resources if appropriate.
                if (freeManagedResources)
                {
                    // Dispose of managed resources here.
                    Console.WriteLine(ProductName + ": Dispose of managed resources");
                }
                // Dispose of unmanaged resources here.
                Console.WriteLine(ProductName + ": Dispose of unmanaged resources");
                // Remember that we have disposed of resources.
                IsResourcesFreed = true;
                // We don't need the destructor because
                // our resources are already freed.
                GC.SuppressFinalize(this);
            }
        }
    }
    

    Summary

    Timely Object cleanup is very important for high performing application. Use Dispose and Finalize wisely in code.

    May 2, 2018 0 comment
    0 Facebook Twitter Google + Pinterest