In this blog I am trying to explain the concept of garbage collector class in C#.
Garbage class
In this class impact when garbage collection is performed on an object and when resources allocated by an object are released. Properties in this class provide information about the total amount of memory available in the system and the age category, or generation, of memory allocated to an object.
The garbage collector tracks and reclaims objects allocated in managed memory. Periodically, the garbage collector performs garbage collection to reclaim memory allocated to objects for which there are no valid references. Garbage collection happens automatically when a request for memory cannot be satisfied using available free memory. Alternatively, an application can force garbage collection using the Collect method.
Garbage collection consists of the following steps:
· The garbage collector searches for managed objects that are referenced in managed code.
· The garbage collector tries to finalize objects that are not referenced.
· The garbage collector frees objects that are not referenced and reclaims their memory.
Example: -
using System;
namespace GCCollectInt
{
class MyGCCollectClass
{
private const long maxGarbage = 1000;
static void Main()
{
MyGCCollectClass myGCCol = new MyGCCollectClass();
Console.WriteLine("The highest generation is {0}", GC.MaxGeneration);
myGCCol.MakeSomeGarbage();
Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));
Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));
GC.Collect(0);
Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));
Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));
GC.Collect(2);
Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));
Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));
Console.Read();
Console.ReadKey();
}
void MakeSomeGarbage()
{
Version vt;
for (int i = 0; i < maxGarbage; i++)
{
vt = new Version();
}
}
}
}
Leave Comment