8.6. 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 that just counts the number of times an action occurs. Use the following method (CreateSimpleCounter) to create a simple custom counter:
public PerformanceCounter CreateSimpleCounter(string counterName, string counterHelp, System.Diagnostics.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 ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access