6.12. Implementing a Simple Performance Counter

Problem

You need to use a performance counter to track application-specific information. The simpler performance counters find, for example, the change in a counter value between successive samplings or just count the number of times an action occurs. Other, more complex counters exist but are not dealt with in this recipe. For example, a custom counter could be built to keep track of the number of database transactions, the number of failed network connections to a server, or even the number of users connecting to your web service per minute.

Solution

Create a simple performance counter that finds, for example, the change in a counter value between successive samplings or to simply count the number of times an action occurs. Use the following method to create a simple custom counter:

public PerformanceCounter CreateSimpleCounter(string counterName, string counterHelp, PerformanceCounterType counterType, string categoryName, string categoryHelp) { CounterCreationDataCollection counterCollection = new CounterCreationDataCollection( ); // Create the custom counter object and add it to the collection of counters CounterCreationData counter = new CounterCreationData(counterName, counterHelp, counterType); counterCollection.Add(counter); // Create category if (PerformanceCounterCategory.Exists(categoryName)) { PerformanceCounterCategory.Delete(categoryName); } PerformanceCounterCategory appCategory = PerformanceCounterCategory.Create(categoryName, ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.