1

We are monitoring a couple of PerformanceCounters every 5 minutes in a Windows-service. Sometimes our code throws:

"Error Message: The Counter layout for the Category specified is invalid, a counter of the type: AverageCount64, AverageTimer32, CounterMultiTimer, CounterMultiTimerInverse, CounterMultiTimer100Ns, CounterMultiTimer100NsInverse, RawFraction, or SampleFraction has to be immediately followed by any of the base counter types: AverageBase, CounterMultiBase, RawBase or SampleBase."

It looks a lot like this problem PerformanceCounter.NextValue() throws InvalidOperationException

I'm not sure when this exception occurs. Sometimes it stable for days and then it's not. When I restart our service it seems solved, but if we just wait it starts working again too. I think it has something to do with incorrect disposing PerformanceCounter. Maybe the GC eventually cleans something so it start working again?

Code:

private static float ReadPerformanceCounter(string CategoryName, string CounterName, string InstanceName)
{
    using (PerformanceCounter performanceCounter = new PerformanceCounter())
    {
        performanceCounter.CategoryName = CategoryName;
        performanceCounter.CounterName = CounterName;
        performanceCounter.InstanceName = InstanceName;

        // will always start at 0
        var firstValue = performanceCounter.NextValue();

        System.Threading.Thread.Sleep(1000);

        // now matches task manager reading
        var secondValue = performanceCounter.NextValue();
        
        return secondValue;
    }
}

It's called like this:

float processor = ReadPerformanceCounter("Processor", "% Processor Time", "_Total");
float disk = ReadPerformanceCounter("PhysicalDisk", "% Disk Time", "_Total");
float memory = ReadPerformanceCounter("Memory", "Page Reads/sec", null);
float networkClient = ReadPerformanceCounter("SMB Client Shares", "Avg. Data Queue Length", "_Total"):
roberth
  • 924
  • 9
  • 17

1 Answers1

1

The problem was that the Performance Counter SMB Client Shares isn't always available (only when the user is logged in and has a network drive-mapping for instance). You have to verify that first.

roberth
  • 924
  • 9
  • 17