#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