Tuesday, October 20, 2015

Use of IDisposable

IDisposble is used for writing object cleanup functionality for our class.
  1. Implement IDisposable and define Dispose() to cleanup managed object
  2. Implement Destructor (Finalizer) to cleanup unmanaged object, do not use Destructor if do not have at least one unmanaged object in class

How to implement?

1. Write Dispose(bool) method
        public void Dispose(bool disposing)
        {
            if (_dispose) return;

            if (disposing)
            {
                //Free managed code
            }

            //Free unmanged code
            _dispose = true;
        }
2. Call Dispose(bool) with true method from actual Dispose() method of IDisposable, to release managed object.
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

Below statement suppress destructor of the class for managed object. 
If we do not write this GC puts some objects in generation 1 and generation 2 also that degrade performance
With this statement GC puts objects in 0th generation that improve performance
GC.SuppressFinalize(this);

3. Call Dispose(bool) with false from destructor to release unmanaged objects.
        ~clsSecurityCritical() //Finalizer
        {
            Dispose(false);
        }
4. GC.SuppressFinalize(thisRequests that the CLR not call the finalizer for the specified object.

Code :
    public class clsSecurityCritical : IDisposable
    {
        public clsSecurityCritical()
        {
   
        }
        public void CallCheck()
        {
            Console.WriteLine("Security Critical code executed");
        }
        ~clsSecurityCritical() //Finalizer
        {
            Dispose(false);
        }

        bool _dispose = false;
        public void Dispose(bool disposing)
        {
            if (_dispose) return;

            if (disposing)
            {
                //Free managed code
            }

            //Free unmanged code
            _dispose = true;
        }

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

    }

No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...