#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: