Garbage Collection in .Net framework


The Garbage collection is very important technique in the .Net framework to free the unused managed code objects in the memory and free the space to the process. I will explain about the basics of the Garbage collection in this article.

Garbage Collection in .Net framework

The garbage collection (GC) is new feature in Microsoft .net framework. When we have a class that represents an object in the runtime that allocates a memory space in the heap memory. All the behavior of that objects can be done in the allotted memory in the heap. Once the activities related to that object is get finished then it will be there as unused space in the memory.
The earlier releases of Microsoft products have used a method like once the process of that object get finished then it will be cleared from the memory. For instance Visual Basic, An object get finishes that work then there we have to define a "nothing" to that object. So, it clears the memory space to the processors.
Microsoft was planning to introduce a method that should automate the cleaning of unused memory space in the heap after the life time of that object. Eventually they have introduced a new technique "Garbage collection". It is very important part in the .Net framework. Now it handles this object clear in the memory implicitly. It overcomes the existing explicit unused memory space clearance.

Garbage Collection

The heap memory is divided into number of generations. Normally it is three generations. The Generation 0 is for short live objects, Generation 1 is for medium live objects which are moved from Generation 0. Generation 3 is mostly stable objects.
When an object is created then it will allocate the memory space which will be higher. It will be in the Generation 0 and the memory allocation will be continuous without any space between the generations of garbage collectors.

How Garbage Collection Works

Implicit Garbage Collection should be handled by the .Net framework. When object is created then it will be placed in the Generation 0. The garbage collection uses an algorithm which checks the objects in the generation, the objects life time get over then it will be removed from the memory. The two kinds of objects. One is Live Objects and Dead Objects. The Garbage collection algorithm collects all unused objects that are dead objects in the generation. If the live objects running for long time then based on that life time it will be moved to next generation.
The object cleaning in the generation will not take place exactly after the life time over of the particular objects. It takes own time to implement the sweeping algorithm to free the spaces to the process.

Exception Handling

The Garbage collection has designed such a way that it can be implicitly handling to collect the free spaces in memory. But as I said it takes own time to uses the algorithm to collect unused objects in the memory.
If we want to forces to collect unused objects or explicitly release particular object from the momory.The code allows us to clear the object from the heap immediately.
When it happens
The garbage collector periodically checks the heap memory to reclaim the objects when the object has no valid references in the memory.
When an object is created then it will allocate the memory in the heap then it checks the available space for the newly created objects, if the available space is not adequate to allot the space then it automatically garbage collect the unused objects. If all are valid referenced objects then it gets additional space from the processor.
If the object has reference with managed code objects then it will not free the memory space. However it cannot control the reference with unmanaged code objects, when application forces to collect the unused objects. But it can be achieved to write the explicit coding to avoid managed objects reference with unmanaged objects. 

Garbage Collection Example code

The Microsoft framework System namespace have the GC class, which exposes more method and property about garbage collection.
This property in the GC class returns the total number of generations.   
  1. using System;  
  2. class GCExample1  
  3. {  
  4.     public static void Main(string[] args)  
  5.     {  
  6.         try  
  7.         {  
  8.             Console.WriteLine("GC Maximum Generations:" + GC.MaxGeneration);  
  9.         }  
  10.         catch (Exception oEx)  
  11.         {  
  12.             Console.WriteLine("Error:" + oEx.Message);  
  13.         }  
  14.     }  
  15. }  
MaxGeneration property will return the highest generation in the garbage collection. It will be counted as total number of generations in the GC class which starts from 0.Here it has returned 2 as maxGeneration. That means totally three generations in the Garbage Collection. They are Generation 0, Generation 1 and Generation 2.  
GetTotalMemory and GetGeneration
  1. using System;  
  2. class BaseGC  
  3. {  
  4.     public void Display()  
  5.     {  
  6.         Console.WriteLine("Example Method");  
  7.     }  
  8. }  
  9. class GCExample2  
  10. {  
  11.     public static void Main(string[] args)  
  12.     {  
  13.         try  
  14.         {  
  15.             Console.WriteLine("Total Memory:" + GC.GetTotalMemory(false));  
  16.             BaseGC oBaseGC = new BaseGC();  
  17.             Console.WriteLine("BaseGC Generation is :" + GC.GetGeneration(oBaseGC));  
  18.             Console.WriteLine("Total Memory:" + GC.GetTotalMemory(false));  
  19.         }  
  20.         catch (Exception oEx)  
  21.         {  
  22.             Console.WriteLine("Error:" + oEx.Message);  
  23.         }  
  24.     }  
  25. }  
Here GetTotalMemory shows the total number of memory occupied by the various resources. Here I have added one more managed code objects in the heap memory. After adding, the size of the memory has increased.
The GetGeneration method will find out the particular managed object in the which generation. Here it shows the Object oBaseGC in the 0th generation. 
CollectionCount and Collect 
  1. using System;  
  2. class Calci  
  3. {  
  4.     public int Add(int a, int b)  
  5.     {  
  6.         return (a + b);  
  7.     }  
  8.     public int Sub(int a, int b)  
  9.     {  
  10.         return (a - b);  
  11.     }  
  12.     public int Multi(int a, int b)  
  13.     {  
  14.         return (a * b);  
  15.     }  
  16.     public int Divide(int a, int b)  
  17.     {  
  18.         return (a / b);  
  19.     }  
  20. }  
  21. class GCExample3  
  22. {  
  23.     public static void Main(string[] args)  
  24.     {  
  25.         Calci oCalci = new Calci();  
  26.         Console.WriteLine("Calci object is now on " + GC.GetGeneration(oCalci) + " Generation");  
  27.         Console.WriteLine("Garbage Collection Occured in 0th Generation:" + GC.CollectionCount(0));  
  28.         Console.WriteLine("Garbage Collection Occured in 1th Generation:" + GC.CollectionCount(1));  
  29.         Console.WriteLine("Garbage Collection Occured in 2th Generation:" + GC.CollectionCount(2));  
  30.         GC.Collect(0);  
  31.         Console.WriteLine("Garbage Collection Occured in 0th Generation:" + GC.CollectionCount(0));  
  32.     }  
  33. } 
The CollectionCount helps us to find out the generation wise garbage collection occurred. As we know there are totally three generations in the garbage collector. Here I have passed argument as one for know the first generation. Initially it was 0. Then through the code I have collected the unused objects in the 0th generation. Again I have checked the CollectionCount in the 0th generation. Now it says 1.
The Collect method used to collect the unreferenced objects in the heap memory. It will clear the object and reclaim the memory space.


So far I explained about the basics of the garbage collection. I have not explained about the explicit handling of the garbage collection ways and some of the methods in the GC class. I will be explaining the part 2 of this article soon. If you found any mistakes or wrong explanations then please indicate me. So that I can update this article.