Garbage collection in C#

What is Garbage collection in C#?

Memory management is the main concern for any application whether an application is window based or web-based. Garbage collection in C# is an automated process of Common Language Runtime (CLR).

In .Net, CLR has a garbage collector that executes as a part of our program and responsible for reclaiming the memory of no longer used objects. Garbage collectors free the memory for objects that are no longer referenced and keeps the memory for future allocations.

Advantages of Garbage Collector:

  1. Reclaims the memory for no longer used objects and keeps the free memory for future allocations.
  2. Provides memory safety by making sure that an object cannot use the content of another object.
  3. Allow us to develop an application without having worry to free memory.
  4. Allocates memory for objects efficiently on the managed heap.

How it works?

There are two ways:

Implicit Resource Management

The finalize method is provided for implicit cleanup in .Net.  In c#, a destructor is written which is implicitly translated to Finalize method.  The finalize method helps to clean up its unmanaged resources held by objects.  By default this method does nothing.  This method has to be overridden to perform cleanup of unmanaged resources like closing the network connection.

class Car
{
     ~car() //destructor
        {
           //cleanup statements
        } 
}

Implicitly Translates to Finalize.

Protected override void Finalize()
{
    try 
      {  
        //clean up statements
      }
    finally
     {
       base.Finalize(); 
     }
}

Important points while implementing Finalize method:

  1. Finalize method is invoked automatically.  So there is no control when this method is invoked for an object.
  2. An object with finalize method may refer to the non-finalizable objects.  Unnecessarily the life time of these objects is prolonged.
  3. Memory pressure increases as finalizable objects are shifted to older generations
  4. If object contains the finalize method, it forces the GC to execute that method.  Here you have to pay performance cost.

The order in which finalize method of various objects is called in not controllable.

Explicit Resource Management

Explicit Resource Management needs to be done when the code contains database connections opened, file handling, and so on.  The explicit resource management can be done by implementing the IDisposable interface for the user defined type.

IDisposable Interface:

If object wants clean up of unmanaged resources explicitly then it implements the interface IDisposable.  Objects must also call the Dispose method of their base class if the base class implements IDisposable interface.

Dispose method:

The Dispose method is used to close or release unmanaged resources such as files, streams, and handles held by an object.  Dispose method is under the control of the developer.

public class ResourceCleaner: IDisposable //Implement IDisposable.
{
    public void Dispose()
     {
       Dispose(true);
       GC.SuppressFinalize(this);
     }

    Protected virtual void Dispose (bool disposing)
      {
        if(disposing)
         {
           // Free other state (managed objects).
         }
        // Free your own state (unmanaged objects).
     }

    ~ResourceCleaner()
       {
          Dispose(false);
       }
}

Generations:

A generational garbage collector collects the short-lived objects more frequently than the longer-lived ones. Short-lived objects are stored in the first generation, generation 0. The longer-lived objects are pushed into the higher generations, 1 or 2. The garbage collector works more frequently in the lower generations than in the higher ones.

When an object is first created, it is put into generation 0. When the generation 0 is filled up, the garbage collector is invoked.

The objects that survive the garbage collection in the first generation are promoted onto the next higher generation, generation 1.

The objects that survive garbage collection in generation 1 are promoted onto the next and the highest generation, generation 2. This algorithm works efficiently for garbage collection of objects, as it is fast. Note that generation 2 is the highest generation that is supported by the garbage collector.

Garbage Collection in C#

Leave a Comment

RSS
Follow by Email
YouTube
YouTube
LinkedIn
Share