I have a C# console application in which I'd like to programatically (without the aid of Visual Studio) monitor GC activity. For example, if I have this code:
public static void Main()
{
for (int i = 0; i < 100000; i++) AllocateByteArray();
}
private static void AllocateByteArray()
{
new byte[1000];
}
Is there a way to use the GC
class to monitor how many times a garbage collection occurs while the loop is running? I initially tried something like this:
Console.WriteLine("Before:");
Console.WriteLine(GC.GetTotalMemory(false));
// do work...
Console.WriteLine("After:");
Console.WriteLine(GC.GetTotalMemory(false));
Console.WriteLine("After collection:");
Console.WriteLine(GC.GetTotalMemory(true));
but I realized the measurements weren't really telling me anything, since a GC probably occurred while I was doing work. I'm not too familiar with the GC APIs in .NET, is there a way to measure these kinds of statistics programatically? Thanks.