Search code examples
c#system.diagnosticsperfmon

Why calling NextValue() on PerformanceCounter object throw error?


Why the following code throws the error Instance 'taskmgr' does not exist in the specified Category. when I don't pass params in ctor

var cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";            
cpuCounter.InstanceName = "taskmgr";
cpuCounter.NextValue();

But, when I do the same by passing params in ctor no error is raised.

var cpuCounter = new PerformanceCounter(
    "Processor",
    "% Processor Time",
    "taskmgr");
cpuCounter.NextValue();

UPDATED: I've tried on every process name, not only "taskmgr" and the result is the same!

What is the problem?


Solution

  • There is no taskmgr instance available for the Processor category because Processor is about your CPUs...

    You probably meant Process, which works as expected:

    var cpuCounter = new PerformanceCounter();
    cpuCounter.CategoryName = "Process";
    cpuCounter.CounterName = "% Processor Time";            
    cpuCounter.InstanceName = "taskmgr";
    cpuCounter.NextValue();