
The C# language is garbage-collected, but getting information about what garbage collection is occurring in your program is not always simple. With the GC.CollectionCount method and GC.MaxGeneration property, you can acquire this information.
Tip: Because most objects die young, generations are used to optimize which elements are scanned. Newer objects are scanned more often because they are most likely to have become dead.
GC.CollectionCount is a method that receives an int argument: the index of the collection generation. Meanwhile, the GC.MaxGeneration property returns the maximum index of the generations. Thus, you can loop through 0 to MaxGeneration and then call CollectionCount on all of those indexes.
This C# example program demonstrates the GC.CollectionCount method. Garbage-collection is generational.
Program that uses CollectionCount [C#]
using System;
class Program
{
static void Main()
{
// This loop does a lot of allocations!
for (int i = 0; i < 100; i++)
{
for (int a = 0; a < 1000; a++)
{
System.IO.Path.GetRandomFileName();
System.IO.Path.GetRandomFileName();
}
System.Threading.Thread.Sleep(1);
}
// Display collection counts.
for (int i = 0; i <= GC.MaxGeneration; i++)
{
int count = GC.CollectionCount(i);
Console.WriteLine(count);
}
}
}
Output
15
0
0
Program output. On my computer, the program resulted in 15 generation 0 garbage collections. This is because the memory allocations caused by GetRandomFileName were all put in generation 0. They died, meaning they lost any reference from the program's flow graph. As is sadly the typical case, these objects died young.
Path.GetRandomFileName MethodWe looked at a program that used the GC.MaxGeneration property as well as the GC.CollectionCount method. With these two static members, we introduced a reliable way of determining the total number of collections for each generation. In the program, we found that the objects died young and were collected.
.NET Framework Info