Counters in C#

Counters in C# are performance counters that allow you to monitor your application's performance metrics in real-time. These counters provide valuable insights into system resources, application behavior, and overall performance characteristics.

When building applications ? whether web, mobile, or desktop ? monitoring performance is crucial for identifying bottlenecks, optimizing resource usage, and ensuring smooth operation under various load conditions.

Syntax

Following is the syntax for creating a performance counter −

PerformanceCounter counter = new PerformanceCounter(categoryName, counterName, instanceName);

Following is the syntax for reading counter values −

float value = counter.NextValue();

Key Properties

The PerformanceCounter class from System.Diagnostics namespace provides several important properties −

  • CategoryName − Specifies the performance counter category (e.g., "Processor", "Memory")

  • CounterName − The name of the specific counter within the category

  • InstanceName − The specific instance to monitor (e.g., "_Total" for overall system)

  • MachineName − The target machine name (default is local machine)

  • ReadOnly − Indicates if the counter is read-only or can be modified

Getting Performance Categories

Example

using System;
using System.Diagnostics;
using System.Linq;

class Program {
   public static void Main() {
      var categories = PerformanceCounterCategory.GetCategories();
      
      Console.WriteLine("Available Performance Counter Categories:");
      Console.WriteLine("Total categories: " + categories.Length);
      
      // Display first 5 categories as example
      for (int i = 0; i < Math.Min(5, categories.Length); i++) {
         Console.WriteLine("- " + categories[i].CategoryName);
      }
   }
}

The output of the above code is −

Available Performance Counter Categories:
Total categories: 245
- .NET CLR Data
- .NET CLR Exceptions
- .NET CLR Interop
- .NET CLR Jit
- .NET CLR Loading

Using Processor Performance Counters

Example

using System;
using System.Diagnostics;
using System.Threading;

class Program {
   public static void Main() {
      // Create a processor counter for CPU usage
      PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
      
      Console.WriteLine("Monitoring CPU Usage:");
      
      // Take 5 readings with 1 second intervals
      for (int i = 0; i < 5; i++) {
         float cpuUsage = cpuCounter.NextValue();
         Console.WriteLine($"Reading {i + 1}: CPU Usage = {cpuUsage:F2}%");
         
         if (i < 4) Thread.Sleep(1000); // Wait 1 second between readings
      }
      
      cpuCounter.Close();
   }
}

The output of the above code is −

Monitoring CPU Usage:
Reading 1: CPU Usage = 0.00%
Reading 2: CPU Usage = 12.45%
Reading 3: CPU Usage = 8.32%
Reading 4: CPU Usage = 15.67%
Reading 5: CPU Usage = 6.89%

Memory Performance Counters

Example

using System;
using System.Diagnostics;

class Program {
   public static void Main() {
      // Monitor available memory
      PerformanceCounter memoryCounter = new PerformanceCounter("Memory", "Available MBytes");
      
      // Monitor private bytes for current process
      string processName = Process.GetCurrentProcess().ProcessName;
      PerformanceCounter processMemory = new PerformanceCounter("Process", "Private Bytes", processName);
      
      Console.WriteLine("Memory Performance Metrics:");
      
      float availableMemory = memoryCounter.NextValue();
      float processPrivateBytes = processMemory.NextValue();
      
      Console.WriteLine($"Available System Memory: {availableMemory} MB");
      Console.WriteLine($"Process Private Bytes: {processPrivateBytes / 1024 / 1024:F2} MB");
      
      memoryCounter.Close();
      processMemory.Close();
   }
}

The output of the above code is −

Memory Performance Metrics:
Available System Memory: 4096 MB
Process Private Bytes: 12.34 MB

Common Use Cases

Counter Category Counter Name Purpose
Processor % Processor Time Monitor CPU utilization
Memory Available MBytes Track available system memory
Process Private Bytes Monitor application memory usage
.NET CLR Memory # Gen 0 Collections Track garbage collection frequency

Conclusion

Performance counters in C# provide essential monitoring capabilities for applications and system resources. Using the PerformanceCounter class, you can track CPU usage, memory consumption, and application-specific metrics to optimize performance and identify potential issues before they impact users.

Updated on: 2026-03-17T07:04:35+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements