Exception: Instance 'Name of instance' does not exist in the specified Category

Aleksandr Vishnyakov picture Aleksandr Vishnyakov · Apr 29, 2011 · Viewed 11.1k times · Source

When I create and use performance counters like this:

private readonly PerformanceCounter _cpuPerformanceCounter;
public ProcessViewModel(Process process)
        {

             _cpuPerformanceCounter = new PerformanceCounter("Process", "% Processor Time", process.ProcessName, true);
        }

public void Update()
        {
            CPU = (int)_cpuPerformanceCounter.NextValue() / Environment.ProcessorCount; // Exception
        }

... I get an exception Instance 'Name of instance' does not exist in the specified Category and don't understand why.

P.S. Code

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.net>
    <settings>
      <performanceCounters enabled="true"/>
    </settings>
  </system.net>
</configuration>

... included in App.config.

Answer

Haukman picture Haukman · Jun 11, 2011

I think your issue happens when there are more than one process with the same name. What PerfMon does then is append #1, #2, etc to the process name. So that means MyApp.exe executed twice will cause this exception when you try to read the performance monitor for "MyApp". Here's a link to one way of solving this: Read performance counters by pid