Creating a new performance counter on Windows with C# .NET

In this post we saw how to list all performance counter categories and the performance counters within each category available on Windows. The last time I checked there were a little more than 27500 counters and 148 categories available on my local PC. That’s quite a lot and will probably cover most diagnostic needs where performance counters are involved in a bottleneck investigation.

However, at times you might want to create your own performance counter. The System.Diagnostics library provides the necessary objects. Here’s how you can create a new performance counter category and a counter within that category:

string categoryName = "Football";
			
if (!PerformanceCounterCategory.Exists(categoryName))
{
	string firstCounterName = "Goals scored";
	string firstCounterHelp = "Goals scored live update";
	string categoryHelp = "Football related real time statistics";
				
	PerformanceCounterCategory customCategory = new PerformanceCounterCategory(categoryName);
	PerformanceCounterCategory.Create(categoryName, categoryHelp, PerformanceCounterCategoryType.SingleInstance, firstCounterName, firstCounterHelp);
}

Read more of this post

Advertisement

Reading the value of a performance counter on Windows with C# .NET

In this post we saw how to list all performance categories and the performance counters within each category. It’s equally straightforward to read the value of a performance counter. You’ll need at least the category and the name of the performance counter. If the counter is available in multiple instances then you’ll need to specify the instance name as well.

The following code will read the CPU usage and memory usage counters:

private static void ReadValuesOfPerformanceCounters()
{
	PerformanceCounter processorTimeCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
	PerformanceCounter memoryUsage = new PerformanceCounter("Memory", "Available MBytes");			
	Console.WriteLine("CPU usage counter: ");
	Console.WriteLine("Category: {0}", processorTimeCounter.CategoryName);
	Console.WriteLine("Instance: {0}", processorTimeCounter.InstanceName);
	Console.WriteLine("Counter name: {0}", processorTimeCounter.CounterName);
	Console.WriteLine("Help text: {0}", processorTimeCounter.CounterHelp);
	Console.WriteLine("------------------------------");
	Console.WriteLine("Memory usage counter: ");
	Console.WriteLine("Category: {0}", memoryUsage.CategoryName);
	Console.WriteLine("Counter name: {0}", memoryUsage.CounterName);
	Console.WriteLine("Help text: {0}", memoryUsage.CounterHelp);
	Console.WriteLine("------------------------------");
	while (true)
	{
		Console.WriteLine("CPU value: {0}", processorTimeCounter.NextValue());
		Console.WriteLine("Memory value: {0}", memoryUsage.NextValue());
		Thread.Sleep(2000);
        }
}

Here’s an excerpt of the output:

Reading values of performance counters

You can view all posts related to Diagnostics here.

Listing all performance counters on Windows with C# .NET

Performance counters in Windows can help you with finding bottlenecks in your application. There’s a long range of built-in performance counters in Windows which you can view in the Performance Monitor window:

Performance Monitor window

Right-click anywhere on the larger screen to the right and select Add Counters to add your counters to the graph. The Add Counters window will show the categories first. You can then open a category and select one or more specific counters within that category. The graph will show the real-time data immediately:

Read more of this post

Listing all performance counters on Windows with C# .NET

Performance counters in Windows can help you with finding bottlenecks in your application. There’s a long range of built-in performance counters in Windows which you can view in the Performance Monitor window:

Performance Monitor window

Right-click anywhere on the larger screen to the right and select Add Counters to add your counters to the graph. The Add Counters window will show the categories first. You can then open a category and select one or more specific counters within that category. The graph will show the real-time data immediately:

Read more of this post

Creating a new performance counter on Windows with C# .NET

In this post we saw how to list all performance counter categories and the performance counters within each category available on Windows. The last time I checked there were a little more than 27500 counters and 148 categories available on my local PC. That’s quite a lot and will probably cover most diagnostic needs where performance counters are involved in a bottleneck investigation.

However, at times you might want to create your own performance counter. The System.Diagnostics library provides the necessary objects. Here’s how you can create a new performance counter category and a counter within that category:

string categoryName = "Football";
			
if (!PerformanceCounterCategory.Exists(categoryName))
{
	string firstCounterName = "Goals scored";
	string firstCounterHelp = "Goals scored live update";
	string categoryHelp = "Football related real time statistics";
				
	PerformanceCounterCategory customCategory = new PerformanceCounterCategory(categoryName);
	PerformanceCounterCategory.Create(categoryName, categoryHelp, PerformanceCounterCategoryType.SingleInstance, firstCounterName, firstCounterHelp);
}

You’ll need to run Visual Studio as an administrator to create the category and counter.

Don’t forget to check if the category exists otherwise you’ll get an exception. The new category and counter turns up in the Performance Monitor window:

Custom category and counter creation result

A slightly different way of creating a new counter is through the CounterCreationData object:

PerformanceCounterCategory customCategory = new PerformanceCounterCategory(categoryName);
CounterCreationData counterCreationData = new CounterCreationData(firstCounterName, firstCounterHelp, PerformanceCounterType.NumberOfItems32);
CounterCreationDataCollection collection = new CounterCreationDataCollection();
collection.Add(counterCreationData);
PerformanceCounterCategory.Create(categoryName, categoryHelp, collection);

If you add that counter to the Performance Monitor then there will be no data yet of course.

At first the counter will be set as read-only but it can be changed easily. The PerformanceCounter object has the Increment() and IncrementBy() methods. Increment() adds 1 to the counter value and IncrementBy() increments the value by the specified amount. You can pass a negative value to decrement the current counter value.

Let’s see these methods in action:

string categoryName = "Football";
string counterName = "Goals scored";
PerformanceCounter footballScoreCounter = new PerformanceCounter(categoryName, counterName);
footballScoreCounter.ReadOnly = false;
while (true)
{
	footballScoreCounter.Increment();
	Thread.Sleep(1000);
	Random random = new Random();
	int goals = random.Next(-5, 6);
	footballScoreCounter.IncrementBy(goals);
	Thread.Sleep(1000);
}

Performance Monitor starts putting the values in the graph:

Goals scored performance counter in Performance Monitor

You can view all posts related to Diagnostics here.

Reading the value of a performance counter on Windows with C# .NET

In this post we saw how to list all performance categories and the performance counters within each category. It’s equally straightforward to read the value of a performance counter. You’ll need at least the category and the name of the performance counter. If the counter is available in multiple instances then you’ll need to specify the instance name as well.

The following code will read the CPU usage and memory usage counters:

private static void ReadValuesOfPerformanceCounters()
{
	PerformanceCounter processorTimeCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
	PerformanceCounter memoryUsage = new PerformanceCounter("Memory", "Available MBytes");			
	Console.WriteLine("CPU usage counter: ");
	Console.WriteLine("Category: {0}", processorTimeCounter.CategoryName);
	Console.WriteLine("Instance: {0}", processorTimeCounter.InstanceName);
	Console.WriteLine("Counter name: {0}", processorTimeCounter.CounterName);
	Console.WriteLine("Help text: {0}", processorTimeCounter.CounterHelp);
	Console.WriteLine("------------------------------");
	Console.WriteLine("Memory usage counter: ");
	Console.WriteLine("Category: {0}", memoryUsage.CategoryName);
	Console.WriteLine("Counter name: {0}", memoryUsage.CounterName);
	Console.WriteLine("Help text: {0}", memoryUsage.CounterHelp);
	Console.WriteLine("------------------------------");
	while (true)
	{
		Console.WriteLine("CPU value: {0}", processorTimeCounter.NextValue());
		Console.WriteLine("Memory value: {0}", memoryUsage.NextValue());
		Thread.Sleep(2000);
        }
}

Here’s an excerpt of the output:

Reading values of performance counters

You can view all posts related to Diagnostics here.

Listing all performance counters on Windows with C# .NET

Performance counters in Windows can help you with finding bottlenecks in your application. There’s a long range of built-in performance counters in Windows which you can view in the Performance Monitor window:

Performance Monitor window

Right-click anywhere on the larger screen to the right and select Add Counters to add your counters to the graph. The Add Counters window will show the categories first. You can then open a category and select one or more specific counters within that category. The graph will show the real-time data immediately:

Performance Monitor with added pre-built categories

The System.Diagnostics namespace has a couple of objects that let you find the available performance categories and counters on the local machine or on another machine. Each performance category has a name, a help text and a type. It’s straightforward to find the categories available on a machine:

PerformanceCounterCategory[] categories = PerformanceCounterCategory.GetCategories();
foreach (PerformanceCounterCategory category in categories)
{
	Console.WriteLine("Category name: {0}", category.CategoryName);
	Console.WriteLine("Category type: {0}", category.CategoryType);
	Console.WriteLine("Category help: {0}", category.CategoryHelp);
}

GetCategories() has an overload where you can specify a computer name if you’d like to view the counters on another computer within the network.

At the time of writing this post I had 161 categories on my machine. Example:

Name: WMI Objects
Help: Number of WMI High Performance provider returned by WMI Adapter
Type: SingleInstance

Once you got hold of a category you can easily list the counters within it. The below code prints the category name, type and help text along with any instance names. If there are separate instances within the category then we need to called the GetCounters method with the instance name if it exists otherwise we’ll get an exception saying that there are multiple instances.

PerformanceCounterCategory[] categories = PerformanceCounterCategory.GetCategories();
foreach (PerformanceCounterCategory category in categories)
{
	Console.WriteLine("Category name: {0}", category.CategoryName);
	Console.WriteLine("Category type: {0}", category.CategoryType);
	Console.WriteLine("Category help: {0}", category.CategoryHelp);
	string[] instances = category.GetInstanceNames();
	if (instances.Any())
	{
		foreach (string instance in instances)
		{
			if (category.InstanceExists(instance))
			{
				PerformanceCounter[] countersOfCategory = category.GetCounters(instance);
				foreach (PerformanceCounter pc in countersOfCategory)
				{
					Console.WriteLine("Category: {0}, instance: {1}, counter: {2}", pc.CategoryName, instance, pc.CounterName);
				}
			}
		}
	}
	else
	{
		PerformanceCounter[] countersOfCategory = category.GetCounters();
		foreach (PerformanceCounter pc in countersOfCategory)
		{
                	Console.WriteLine("Category: {0}, counter: {1}", pc.CategoryName, pc.CounterName);
		}
	}	
}

Each counter in turn has a name, a help text and a type. E.g. here’s a counter with the “Active Server Pages” category:

Name: Requests Failed Total
Help: The total number of requests failed due to errors, authorization failure, and rejections.
Type: NumberOfItems32

You can view all posts related to Diagnostics here.

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: