Why does accessing a PerformanceCounter cause gen2

2019-04-10 03:19发布

问题:

Im seeing some strange behavior when I access certain PerformanceCounters from within a C# application. For example when I access Process - Private Bytes it seems I get a lot of generation 2 garbage collections (the same seems to be true for other Process counters).

The below program demonstrates this. If you run it every 8 seconds or so I see a gen2 collection. If I remove the _privateBytesCounter.NextValue() I do not see any gen2 collections at all.

Can anyone explain this?

I am running Visual Sudio 2015 and targeting .NET 4.5.2.

using System;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;

namespace Gen2Collections
{
    class Program
    {
        private static PerformanceCounter _privateBytesCounter;
        private static PerformanceCounter _gen2Counter;

        static void Main(string[] args)
        {
            _privateBytesCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName);
            _gen2Counter = new PerformanceCounter(".NET CLR Memory", "# Gen 2 Collections", Process.GetCurrentProcess().ProcessName);
            RunMonitor();
            Thread.Sleep(60000);
        }
        private static void RunMonitor()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    _privateBytesCounter.NextValue();
                    Console.WriteLine(_gen2Counter.NextValue());
                    Thread.Sleep(1000);
                }
            });
        }
    }
}