Creating a new performance counter on Windows with C# .NET

In this post we saw how to list all performance counter categories and the performance counters within each category available on Windows. The last time I checked there were a little more than 27500 counters and 148 categories available on my local PC. That’s quite a lot and will probably cover most diagnostic needs where performance counters are involved in a bottleneck investigation.

However, at times you might want to create your own performance counter. The System.Diagnostics library provides the necessary objects. Here’s how you can create a new performance counter category and a counter within that category:

If you add that counter to the Performance Monitor then there will be no data yet of course.

At first the counter will be set as read-only but it can be changed easily. The PerformanceCounter object has the Increment() and IncrementBy() methods. Increment() adds 1 to the counter value and IncrementBy() increments the value by the specified amount. You can pass a negative value to decrement the current counter value.