MSDN

.NET Framework Documentation

PerformanceCounter Class

The PerformanceCounter class in the System.Diagnostics namespace provides a managed wrapper for Windows performance counter objects. It allows you to read performance data from the operating system, such as CPU utilization, memory usage, disk I/O, and custom application-specific counters.

Namespace:

System.Diagnostics

Assembly:

System.dll

Syntax:

public sealed class PerformanceCounter

Remarks:

Performance counters are a powerful tool for monitoring the health and performance of your applications and the underlying system. The PerformanceCounter class simplifies the process of interacting with these counters.

You can create a PerformanceCounter instance by specifying the counter category, the counter name, and optionally the instance name. If the counter is a single instance counter, the instance name can be an empty string. For multi-instance counters, you need to provide the specific instance name.

The PerformanceCounter class supports both built-in system counters and custom counters that you can create and expose from your application.

Note: Accessing performance counters typically requires appropriate permissions. Ensure your application has the necessary privileges to read performance data.

Constructors:

Constructor Description
PerformanceCounter() Initializes a new instance of the PerformanceCounter class with default settings.
PerformanceCounter(string categoryName, string counterName) Initializes a new instance of the PerformanceCounter class, specifying the counter category and name.
PerformanceCounter(string categoryName, string counterName, string instanceName) Initializes a new instance of the PerformanceCounter class, specifying the counter category, name, and instance name.
PerformanceCounter(string categoryName, string counterName, string instanceName, bool readOnly) Initializes a new instance of the PerformanceCounter class, specifying the counter category, name, instance name, and whether it should be read-only.

Properties:

Property Description
CategoryName Gets the name of the performance counter category.
CounterName Gets the name of the performance counter.
InstanceName Gets the name of the performance counter instance.
ReadOnly Gets a value indicating whether the performance counter is read-only.
RawValue Gets or sets the raw value of the performance counter.
CookedValue Gets the counter's value, formatted for display.
CounterHelp Gets the help text for the performance counter.

Methods:

Method Description
Increment() Increments the value of a counter by one.
IncrementBy(long value) Increments the value of a counter by the specified amount.
Decrement() Decrements the value of a counter by one.
NextValue() Retrieves the next sampled value of the performance counter.
NextSample() Retrieves the next sample for the performance counter.
Close() Releases all resources used by the PerformanceCounter.
Dispose() Releases all resources used by the PerformanceCounter.

Example:

The following example demonstrates how to read the current CPU utilization:

using System;
using System.Diagnostics;

public class CpuMonitor
{
    public static void Main(string[] args)
    {
        try
        {
            // Create a PerformanceCounter instance for CPU utilization
            // Category: Processor, Counter: % Processor Time, Instance: _Total
            PerformanceCounter cpuCounter = new PerformanceCounter(
                "Processor",
                "% Processor Time",
                "_Total",
                true); // Read-only

            // Get the initial value to establish a baseline
            cpuCounter.NextValue();

            // Wait for a short period
            System.Threading.Thread.Sleep(1000);

            // Get the current CPU utilization
            float cpuUsage = cpuCounter.NextValue();

            Console.WriteLine($"Current CPU Usage: {cpuUsage:N2}%");

            cpuCounter.Dispose(); // Release resources
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine($"Error accessing performance counter: {ex.Message}");
            Console.WriteLine("Ensure the 'Processor' category and '% Processor Time' counter exist and you have permissions.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An unexpected error occurred: {ex.Message}");
        }
    }
}
Tip: You can use the Performance Monitor (perfmon.msc) utility in Windows to explore available performance counter categories and counters on your system.

Related Topics: