As Kieran already pointed out, adding perfomance counters is not something you should do in runtime. The recommended manner is to create an executable that registers the performance counters, then later you can reference these custom counters from your application. Here is a sample of how such a executable could look:
using System;
using System.Diagnostics;
namespace RegisterPerformanceCounters
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("(R)egister counters?");
Console.WriteLine("(D)elete counters?");
Console.WriteLine("(C)ancel?");
switch (Console.ReadLine().ToUpper())
{
case "R":
Console.WriteLine("Registering counters...");
CreateCounters();
break;
case "D":
Console.WriteLine("Deleting counters...");
DeleteCounters();
break;
case "C":
break;
default:
Console.WriteLine("Invalid choise.");
break;
}
Console.WriteLine("Done.");
Console.ReadLine();
}
static void CreateCounters()
{
CounterCreationDataCollection col = new CounterCreationDataCollection();
// Create two custom counter objects.
CounterCreationData counter1 = new CounterCreationData();
counter1.CounterName = "Counter1";
counter1.CounterHelp = "Custom counter 1";
counter1.CounterType = PerformanceCounterType.CounterTimer;
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("Category Name"))
PerformanceCounterCategory.Create(
"Category Name",
"Category Description",
col);
else Console.WriteLine("Counters already exists");
}
static void DeleteCounters()
{
// Check if the category already exists or not.
if (PerformanceCounterCategory.Exists("Category Name")) PerformanceCounterCategory.Delete("Category Name");
else Console.WriteLine("Counters don't exist.");
}
}
, you only need to register the performance counters once. Later when you wan't to use the performance counters it may look something like this:
// Get an instance of our perf counter
PerformanceCounter counter = new PerformanceCounter();
counter.CategoryName = "Category Name";
counter.CounterName = "Counter1";
counter.ReadOnly = false;
// Increment and close the perf counter
counter.Increment();
counter.Close();
Response.Write("Counter is incremented");
See article in MSDN Library for more information.