How to work with performance counters in C#

Take advantage of performance counters to get an insight on the performance of your applications

Performance counters

Performance counters

Windows keeps a watch of the processes and services that are running in your system by tracking of the threads that are currently in execution, the CLR memory, etc. You would often need to measure the performance of computer systems or the applications running on them according to metrics like for the resource consumption in the system, services running on the system, or the performance of the devices attached to the system.

Performance counters (a feature provided by default) enable us to capture, publish and analyze the performance data related to one or more applications or services running in the system or the system as a whole.

While building applications, you might often need to monitor its performance (resource consumption or usage over a period of time) and use the performance data to identify the bottlenecks in the application. Here's where performance counters come in handy. You can also use WMI (Windows Management Instrumentation), a COM based Microsoft technology, to retrieve these details, but performance counters provide you a way to get the real time statistics of the resource consumption in your system at runtime.

The Performance Monitor (a tool provided by default in Windows OS) snap-in can be used to view the performance data in real time. To start this tool, click on the Start menu and click on "Run". Next, type "perfmon" and press enter.

Custom Performance Counters

Creating custom performance counters is simple. You can create performance counters using the Server Explorer. You would need to create the performance counter category first and then create one or more counters as part of that category.

To work with performance counters programmatically, you can use the System.Diagnostics.PerformanceCounter class. You would need to create an instance of the PerformanceCounter class and then specify the necessary values for each of these properties: CategoryName, CounterName, MachineName and ReadOnly.

To create a custom performance counter category you would need to leverage the Create method of the PerformanceCounterCategory class. As an example, the following code snippet can be used to create a custom performance counter category.

PerformanceCounterCategory.Create("CustomPerformanceCounterCategoryName", "CustomPerformanceCounterHelp", PerformanceCounterCategoryType.MultiInstance,

"CustomPerformanceCounterName", "CustomPerformanceCounterHelp");

The following code snippet shows how you can display all the performance counter categories available.

static void Main()

    {

        var performanceCounterCategories = PerformanceCounterCategory.GetCategories();

        foreach(PerformanceCounterCategory performanceCounterCategory in performanceCounterCategories)

        {

         Console.WriteLine(performanceCounterCategory.CategoryName);

        }

        Console.Read();

    }

The following code snippet illustrates how you can retrieve performance counters that belong to the category "Processor".

var performanceCounterCategories = PerformanceCounterCategory.GetCategories()

     .FirstOrDefault(category => category.CategoryName == "Processor");

var performanceCounters = performanceCounterCategories.GetCounters("_Total");

You need to use the PerformanceCounter class to read a performance counter belonging to a particular category. Note that the PerformanceCounter class is available in the System.Diagnostics namespace. Here's the complete code listing that shows how you can display the performance counter names of all the performance counters that belong to the "Processor" category.

static void Main()

    {

        var performanceCounterCategories = PerformanceCounterCategory.GetCategories()

            .FirstOrDefault(category => category.CategoryName == "Processor");

        var performanceCounters = performanceCounterCategories.GetCounters("_Total");

        Console.WriteLine("Displaying performance counters for Processor category:--\n");

        foreach (PerformanceCounter performanceCounter in performanceCounters)

        {

            Console.WriteLine(performanceCounter.CounterName);

        }

        Console.Read();

    }

You can also create your custom performance counter and write data in them. To do this, you should take advantage of the CounterCreationDataCollection and CounterCreationData classes.

String customCategory = "Custom Performance Counter Category";

if (!PerformanceCounterCategory.Exists(customCategory))

{

CounterCreationDataCollection counterCreationDataCollection = new CounterCreationDataCollection();

counterCreationDataCollection.Add(new CounterCreationData("Counter 1", "Sample Counter 1", PerformanceCounterType.ElapsedTime));

counterCreationDataCollection.Add(new CounterCreationData("Counter 2", "Sample Counter 2", PerformanceCounterType.SampleCounter));

counterCreationDataCollection.Add(new CounterCreationData("Counter 3", "Sample Counter 3", PerformanceCounterType.SampleCounter));

PerformanceCounterCategory.Create(customCategory, "This is just an example", PerformanceCounterCategoryType.SingleInstance, counterCreationDataCollection);

}

Note that a check if made to validate if the custom performance counter to be created already exists. The custom performance counter is only created if it doesn't exist. Next, an instance of CounterCreaionDataCollection is created. Using the CounterCreationData class, new counters are added to the collection. Once the necessary counters have been added, the Create method of the PerformanceCounterCategory class is called to create the custom performance category.

Note that your application should have the necessary permissions to access the performance counters you need. I would always recommend starting Visual Studio IDE in the Administrator mode. Performance counters help a lot to analyze the performance of your applications -- you can analyze the performance data at the time when your application is in execution.

This article is published as part of the IDG Contributor Network. Want to Join?

To comment on this article and other InfoWorld content, visit InfoWorld's LinkedIn page, Facebook page and Twitter stream.
From CIO: 8 Free Online Courses to Grow Your Tech Skills
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.