Wednesday, January 16, 2008

Performance Counter

PerformanceCounterCategory class can be used to create key and type-value inside it.
It creates it under "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services" in the regedit.

PerformanceCounterCategory.Exists - weather the specified custom counter exists.
PerformanceCounterCategory.Create - creates a new custom counter.

Eg:

if (!PerformanceCounterCategory.Exists("MySingleCategory"))
{
PerformanceCounterCategory.Create ("MySingleCategory",
"My New Perf Category Description", "MyCounter",
"My New Perf Counter Desc");
}
else
{
Console.WriteLine("Counter already exists");
}


Another class 'CounterCreationDataCollection' can be used to add more then one custom counter. Create multiple instance of counter using 'CounterCreationData'. Add them to the collection and create the performanceCounterCategory using this collection.


Eg:

CounterCreationDataCollection col =
new CounterCreationDataCollection();

// Create two custom counter objects.
CounterCreationData counter1 = new CounterCreationData();
counter1.CounterName = "Counter1";
counter1.CounterHelp = "Custom counter 1";
counter1.CounterType = PerformanceCounterType.NumberOfItemsHEX32;

CounterCreationData counter2 = new CounterCreationData();

// Set the properties of the 'CounterCreationData' object.
counter2.CounterName = "Counter2";
counter2.CounterHelp = "Custom counter 2";
counter2.CounterType = PerformanceCounterType.NumberOfItemsHEX32;

// Add custom counter objects to CounterCreationDataCollection.
col.Add(counter1);
col.Add(counter2);

// Bind the counters to a PerformanceCounterCategory
// Check if the category already exists or not.
if(!PerformanceCounterCategory.Exists("MyMultipleCategory"))
{
PerformanceCounterCategory category =
PerformanceCounterCategory.Create("MyMultipleCategory",
" My New Perf Category Description ", col);
}
else
{
Console.WriteLine("Counter already exists");
}


To access a already existing performance counter. Use the 'category name' and 'counter name' to make the performance counter accessible.

Eg:

PerformanceCounter counter = new PerformanceCounter();
counter.CategoryName = "mySingleCategory";
counter.CounterName = "myCounter";
counter.ReadOnly = false;

No comments: