Thursday, August 23, 2007

Adding a performance counter

Some times you need to measure the value of something while running the application.
Using a logger is not comfortable, since you don't want to monitor gazillion rows of values.
The solution: create a performance counter and use Perfmon.exe to view it while the application is running.

Here is a code for creating a counter:

private PerformanceCounter CreatePerformanceCounter()
{
string categoryName = "My Category";

if ( !PerformanceCounterCategory.Exists(categoryName) )
{
CounterCreationDataCollection CCDC = new CounterCreationDataCollection();

// Add the counter.
CounterCreationData myCounter = new CounterCreationData();
myCounter.CounterType = PerformanceCounterType.NumberOfItems64;
myCounter.CounterName = "My Counter";
CCDC.Add(myCounter);

// Create the category.
PerformanceCounterCategory.Create("categoryName", "This is my cateogory", CCDC);
}

PerformanceCounter result = new PerformanceCounter(categoryName, "My Counter", false);
}

Note: You'll need an administrator account to create a new category, but once it's there any account it OK.

No comments: