Performance counters helps you monitor the status of a given application, and identify bottlenecks. You can view performance counters in the Computer Management tool, by selecting the Performance (or Reliability &Performance) tab.
To access performance counters programmatically, you’ll use the PerformanceCounter class. To read from an existing counter, use the following method:
PerformanceCounter pc = new PerformanceCounter(“Processor”, “% Processor Time”, “_Total”);
It is important to call the NextValue method (which returns the change between two calls) for the first time, since it resets the counter, and starts to collect data from it.
You can add your custom performance counters, too. To do so, use the overloaded PerformanceCounterCategory.Create method. With it, you can create a new performance counter category, and add instances to it.
To modify the values of performance counters, you have four methods:
- RawValue: assign a long to the counter. Beware: this method isn’t thread safe, however, it’s five times faster than the others.
- Increment: increments the value by one. Creates a lock during the incrementation, so it’s thread safe.
- Decrement: decrements the value by one. Thread safe.
- IncrementBy(long): increments the value by the specified long. Thread safe.