BlackWaspTM
System Information
.NET 1.1+

Reading Performance Counters (2)

Microsoft Windows provides a large number of categorised performance counters that can be used to monitor the utilisation of hardware, services, software applications and drivers. Usually viewed with Performance Monitor, they can also be read using C#.

Reading a Multi-Instance Counter

When reading a performance counter that has multiple instances, you must specify the instance to read using the InstanceName property. You can also use another variation upon the PerformanceCounter constructor. This version accepts the instance name as a third argument. The second performance counter that we will interrogate is the "% Processor Time" counter that resides within the "Processor" category. This counter has instances for each processor as well as an instance named "_Total" that returns the combined processor utilisation.

To attach to the new performance counter add the following class-scope declaration:

private PerformanceCounter _processorCounter
    = new PerformanceCounter("Processor", "% Processor Time", "_Total");

You can now add the following line of code to the Tick event to display the counter value in the other Label control:

ProcessorLabel.Text = _processorCounter.NextValue().ToString("0.0");

When you run the program, you may notice that the processor utilisation value is initially set to zero. This is because the performance counter is a two-read counter. Such counters return incremental values that represent the average or total for the period between calls to the NextValue method.

5 October 2009