Joydip Kanjilal
Contributor

How to work with performance counters in C#

opinion
Nov 25, 20154 mins
Software Development

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

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.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author