#667 – .NET Memory Performance Counters Updated When Garbage Collector Runs

The .NET CLR Memory performance counters can be used to track memory usage for CLR-based (.NET) applications.  The counters, however, are only updated when the garbage collector runs.  This means that if you’re watching one of the counters, you won’t necessarily see it update immediately after your application allocates some memory.

If you are doing some debugging or profiling related to memory management, you can force garbage collection at the point where you want to measure memory usage.  You do this using the GC.Collect method.  GC.Collect should not typically be called explicitly in production code.

    public class Program
    {
        private static List<object> _bigList = new List<object>();

        static void Main()
        {
            try
            {
#if DEBUG
                GC.Collect();
#endif

                while (true)
                {
                    ConsoleKeyInfo cki = Console.ReadKey();

                    int size = 1024 * 1024;  // 1MB
                    byte[] data = new byte[size];

                    Array.Clear(data, 0, size);

                    _bigList.Add(data);

#if DEBUG
                    GC.Collect();
#endif
                }
            }
            catch (Exception xx)
            {
                Console.WriteLine(xx.ToString());
                Console.ReadLine();
                }
        }
    }
Advertisements

#424 – The Garbage Collector

In C#, you don’t explicitly delete heap-based objects.  Instead, the CLR will reclaim memory from objects that are no longer used, by running a Garbage Collector.

The garbage collector (GC) can release memory only for managed objects created on the heap.  It’s only job is to release memory.  It can’t clean up or release other resources, like file handles or database connections.

The GC will typically perform garbage collection when the amount of available physical memory is becoming too low or when the amount of virtual memory consumed by your application is becoming too large.

You can’t predict when garbage collection is going to happen, or even if it’s going to happen, prior to an application terminating.