0

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.

James Ko
  • 32,215
  • 30
  • 128
  • 239
  • https://msdn.microsoft.com/en-us/library/w8f5kw2e(v=vs.110).aspx – Mitch Wheat Jun 11 '16 at 01:39
  • Additional GC related reading: [Everybody thinks about garbage collection the wrong way](https://blogs.msdn.microsoft.com/oldnewthing/20100809-00/?p=13203), [When does an object become available for garbage collection?](https://blogs.msdn.microsoft.com/oldnewthing/20100810-00/?p=13193) and When Everything you know is wrong [Part 1](https://ericlippert.com/2015/05/18/when-everything-you-know-is-wrong-part-one/) [Part 2](https://ericlippert.com/2015/05/21/when-everything-you-know-is-wrong-part-two/) – theB Jun 11 '16 at 01:47

2 Answers2

1

I can't say I know remotely enough to be directly helpful, but there are a couple things I pulled up when I went hunting for an answer in curiosity. Hopefully these things are not irrelevant in light of the specific bit about "without the aid of Visual Studio"

There's another thread here on SO about this. Monitoring Garbage Collector in C#

And MSDN does have some documentation with regard to it. https://msdn.microsoft.com/en-us/library/ee851764(v=vs.110).aspx

For me, the garbage collector is a pretty mystical thing, still.

Community
  • 1
  • 1
1

If you are not doing background garbage collection, you can use an event based system to receive garbage collection notifications.

The RegisterForFullGCNotification method registers for a notification to be raised when the runtime senses that a full garbage collection is approaching. There are two parts to this notification: when the full garbage collection is approaching and when the full garbage collection has completed.

Note the warning that this doesn't work for background collection

Only blocking garbage collections raise notifications. When the <gcConcurrent> configuration element is enabled, background garbage collections will not raise notifications.

Eric J.
  • 147,927
  • 63
  • 340
  • 553