Listing 1
using System;
using System.Diagnostics;
namespace MyCounter
{
class SimpleCounter
{
/// <summary>
/// Provides an example of creating a simple performance counter from .NET
/// </summary>
[STAThread]
static void Main(string[] args)
{
PerformanceCounter pcTotalLoops;
int i;
//check to see if the counter exists...
if (!PerformanceCounterCategory.Exists(".NET Journal Counter"))
{
//create the counter category
PerformanceCounterCategory.Create(".NET Journal Counter",
"A sample counter for .NET Developers Journal Readers.",
"Total Loops","Tracks how many times we looped.");
}
//obtain an instance of the counter.
pcTotalLoops = new PerformanceCounter(".NET Journal Counter","Total Loops","CounterExample",false);
for (i=0;i<10;i++)
{
//increment the counter value.
pcTotalLoops.Increment();
Console.WriteLine("Loop Value = " + i);
}
Console.WriteLine("Done looping...");
//check counter value.
Console.WriteLine("Your Counter Value = " + pcTotalLoops.RawValue);
//removes the counter...
if (PerformanceCounterCategory.Exists(".NET Journal Counter"))
{
Console.WriteLine("Press Enter to delete your custom counter...");
Console.Read();
PerformanceCounterCategory.Delete(".NET Journal Counter");
}
}
}
}