Let’s understand about the generation of garbage collection
Here are three generations of the Garbage Collection and it is listed out below.
Generation 0: All the shorted objects such as Temp variables contained in Gen 0 of the mass memory. Here all newly allocated objects are also gen 0 objects implicitly unless they are big objects. In general, the 0 Gen have a big collection of regularity.
Generation 1: If space active by some generation 0 objects that are not released in a garbage collection run, then these objects get moved to generation 1. In this generation objects are sort of buffer between the short object in Gen 0 and the big objects in gen 2.
Generation 2: If space used by some gen 1 objects are not released in the again garbage collection run, then these objects get moved to generation 2. The objects in second generation are long-lived such as static objects that remained in the heap memory for the whole process duration.
GC.MaxGeneration property of the Garbage Collection class is given as follows:
using System;
public class GCDemo {
public static void Main(string[] args)
{
Console.WriteLine("The no. of generations in Garbage collection: " +
GC.MaxGeneration);
}
}
GetTotalMemory and GetGeneration
using System;
class BaseGC
{
public void Dis()
{
Console.WriteLine("Example of the Garbage Collection");
}
}
class GCExample2
{
public static void Main (string [] args)
{
try
{
Console.WriteLine("Total Memory:" + GC.GetTotalMemory(false));
BaseGC oBaseGC = new BaseGC();
Console.WriteLine("Base GC Generation is :" + GC.GetGeneration(oBaseGC));
Console.WriteLine("Total Memory:" + GC.GetTotalMemory(false));
}
catch (Exception oEx)
{
Console.WriteLine("Error:" + oEx.Message);
}
}
}
Here GetTotalMemory this method shows the total number of memories occupied by the different resources. Here we have added one more managed code object in the heap memory. After including, the size of the memory has extended.
How to implement garbage collection in .NET, let’s understand using step by step simple example.
using System;
class
{
public int Add(int x, int y)
{
return (x + y);
}
public int Sub(int x, int y)
{
return (x - y);
}
public int Mult(int x, int y)
{
return (x * y);
}
public int Divide(int x, int y)
{
return (x / y);
}
}
class GCExample3
{
public static void Main(string[] args)
{
o = new ();
Console.WriteLine(" then right now object on " + GC.GetGeneration(o) + " Generation");
Console.WriteLine("Garbage Collection Occurred in 0th Generation:" + GC.CollectionCount(0));
Console.WriteLine("Garbage Collection Occurred in 1th Generation:" + GC.CollectionCount(1));
Console.WriteLine("Garbage Collection Occurred in 2th Generation:" + GC.CollectionCount(2));
GC.Collect(0);
Console.WriteLine("Garbage Collection Occurred in 0th Generation:" + GC.CollectionCount(0));
}
}