When we are working with C# .Net framework, we must use the Garbage Collector to make sure we do not use the unnecessary code objects in the stack of the memory as well as we can free the unwanted space for the process. Here, we will discuss the Garbage Collector regarding the C# .Net.
Garbage collection is a critical aspect that is highly focused on by any .NET development company while in their project development. It resolves memory issues and effortlessly manages various objects in the project. It is the latest feature in the .NET Framework. When we are working with a class that will represent the object in the runtime which will allocate the memory space in the hap of the memory. As the activities which are related to the object are finished then they will be used because there will be unused space in the memory. It will overcome the existing explicit unused memory clearance of space.
Garbage Collection in C# .NET
Normally, the heap of the memory is divided into a few numbers of generations: Generation 0, Generation 1, and Generation 2. Here, Generation 0 is associated with short live objects, Generation 1 for medium live objects, and Generation 2 for stable objects.
When we create an object, it will be allocated the memory space which might be higher and will be in Generation 0, and the memory allocation would be continuous without any space between the generations of the garbage collectors.
How does Garbage Collection work?
Usually, the Garbage Collection is handled by the .NET Framework implicitly. At the time of object creation, it will be assigned to Generation 0. The garbage collection will use an algorithm that will check the objects in the generation, the lifetime of the object will get over, and then it will be removed from the memory.
There are mainly two types of objects: Live Objects and Dead Objects. The Garbage collector will collect all the unused objects that are dead in the respectful generation. If there is any live object which is running for a long time, then based on the lifetime, it will be moved to the next generation.
Exception Handling
The process of Garbage Collection is designed so well that it can be implicitly collect the free spaces in the memory of the heap. But it might take own time to use the algorithm to collect the unused objects in the heap of the memory. When we want to force collect the unused objects or indirectly release the specific object from the heap of the memory. The code will allow us to clear the object from the heap at the immediate moment.
When will Garbage Collection Happen?
The process of the garbage collector checks the heap of the memory to get back the objects when the object has no actual references in the heap of the memory.
At the time of the creation of the object, it will be allocated the memory in the heap. Next, it will check the available space for the new objects which are freshly created; if the available space is not enough to allot, the garbage collector will automatically collect the unused objects. If there all are valid referenced objects, then and only then it will get additional space for the processor.
If there is a situation where the object has one or more references with the managed code objects, then it will not allow the heap memory to be free. However, it cannot control the reference with the unmanaged code objects, when the application forces to collect the unused objects, but this situation can be achieved to write the independent coding to avoid the managed objects references with dependent objects.
Examples:
In the .NET Framework, the System namespace has the GC Class, which will expose more methods and properties about garbage collection.
1. MaxGeneration:
This property is used in the GC Class to return the total number of generations. Here is a small example of it:
using System;
class GCExample1
{
public static void Main(string[] args)
{
try
{
Console.WriteLine(“GC Maximum Generations:” + GC.MaxGeneration);
}
catch (Exception oEx)
{
Console.WriteLine(“Error:” + oEx.Message);
}
}
}
The MaxGeneration property will return the highest generation in the whole process of the garbage collection. It will be numbered as a total number of the generations in the GC Class which will start from 0. In this code snippet, it will return 2 as maxGeneration, which means there is a total of three generations in the garbage collection. As we discussed, there is a total of three generations: Generation 0, Generation 1, and Generation 2.
2. GetTotalMemory and GetGeneration:
using System;
class BaseGC
{
public void Display()
{
Console.WriteLine(“Example Method”);
}
}
class GCExample2
{
public static void Main(string[] args)
{
try
{
Console.WriteLine(“Total Memory:” + GC.GetTotalMemory(false));
BaseGC oBaseGC = new BaseGC();
Console.WriteLine(“BaseGC Generation is :” + GC.GetGeneration(oBaseGC));
Console.WriteLine(“Total Memory:” + GC.GetTotalMemory(false));
}
catch (Exception oEx)
{
Console.WriteLine(“Error:” + oEx.Message);
}
}
}
The GetTotalMemory will show the total number of bits of memory occupied by the different resources. Here we have added one more managed code object in the heap of the memory. After adding, the size of the memory will increase.
The GetGeneration method will find out the particular managed object in the specific generation it stands for. In this code snippet, it will show the object in the 0th generation.
3. CollectionCount and Collect:
using System;
class Calci
{
public int Add(int a, int b)
{
return (a + b);
}
public int Sub(int a, int b)
{
return (a – b);
}
public int Multi(int a, int b)
{
return (a * b);
}
public int Divide(int a, int b)
{
return (a / b);
}
}
class GCExample3
{
public static void Main(string[] args)
{
Calci oCalci = new Calci();
Console.WriteLine(“Calci object is now on ” + GC.GetGeneration(oCalci) + ” Generation”);
Console.WriteLine(“Garbage Collection Occured in 0th Generation:” + GC.CollectionCount(0));
Console.WriteLine(“Garbage Collection Occured in 1th Generation:” + GC.CollectionCount(1));
Console.WriteLine(“Garbage Collection Occured in 2th Generation:” + GC.CollectionCount(2));
GC.Collect(0);
Console.WriteLine(“Garbage Collection Occured in 0th Generation:” + GC.CollectionCount(0));
}
}
The CollectorCount will help us to find the generation-wise garbage collection data. In this code snippet, we have passed the argument as one to know the first generation. At the starting phase, it will be 0. Then as we collect the unused objects in the 0th generation, it will be updated to 1st generation.
Conclusion
In this article, we have discussed the basics of Garbage collection, and methods of garbage collection. We have also gone through examples that will help you to understand how the garbage collection process occurs.
Check out all the software testing webinars and eBooks here on EuroSTARHuddle.com