Partager via


How To: Use Custom Performance Counters from ASP.NET

 

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

patterns & practices Developer Center

Improving .NET Application Performance and Scalability

J.D. Meier, Srinath Vasireddy, Ashish Babbar, and Alex Mackman
Microsoft Corporation

May 2004

Related Links

Home Page for Improving .NET Application Performance and Scalability

Chapter 15, Measuring .NET Application Performance

Chapter 6, Improving ASP.NET Performance

Send feedback to Scale@microsoft.com

patterns & practices Library

Summary: This How To shows you how to create custom performance counters and use them to monitor ASP.NET application performance. Performance counters can help you fine-tune your application and maximize the performance of the code you have written.

Contents

Applies To
Overview
Creating Performance Counters
Creating a Single Performance Counter Using PerformanceCounterCategory
Creating Multiple Performance Counters Using CounterCreationDataCollection
Using Server Explorer
Using Your Performance Counter in Code
Monitoring Your Performance Counter
Additional Resources

Applies To

  • Microsoft® .NET Framework version 1.1

Overview

You can instrument your code with custom performance counters. The System.Diagnostics namespace provides access to the performance counter libraries. You should create your custom performance counters outside ASP.NET, by using either a console application or Microsoft Visual Studio® .NET Server Explorer. You can then use Performance Monitor to view your custom performance counters' activity.

Creating Performance Counters

You should create your performance counters outside ASP.NET. Creating a performance counter category requires permissions that the default ASP.NET account does not have. The ASP.NET account can read the custom performance counters once they have been created. Do not run ASP.NET as SYSTEM or as an administrative account because doing so poses a security risk.

Creating a Single Performance Counter Using PerformanceCounterCategory

If you only need to create a single counter, you can use PerformanceCounterCategory to do so. If you need to create multiple performance counters, see "Creating Multiple Performance Counters Using CounterCreationDataCollection," later in this How To.

To create a single performance counter using PerformanceCounterCategory

  1. Create a new text file named CreateCounter.cs and add the following code.

    // CreateCounter.cs
    
    using System;
    using System.Diagnostics;
    
    public class CustomCounter
    {
      public static void Main()
      {
        Console.WriteLine("Creating custom counter");
        CreateCounter();
        Console.WriteLine("Done");
        Console.ReadLine();
      }
    
      public static void CreateCounter()
      {
        if (!PerformanceCounterCategory.Exists("MySingleCategory"))
        {
          PerformanceCounterCategory.Create ("MySingleCategory",
                         "My New Perf Category Description", "MyCounter",
          "My New Perf Counter Desc");
        }
        else
        {
          Console.WriteLine("Counter already exists");
        }
      }
    }
    
  2. Compile the code using the following command line.

    csc.exe /out:CreateCounter.exe /t:exe /r:system.dll CreateCounter.cs
    
  3. Run CreateCounter.exe from a command prompt to create your new performance counter.

    CreateCounter.exe
    

Results

When you run CreateCounter.exe, the following output is produced.

Creating custom counter
Done

Validating Your Performance Counter Category and Performance Counter

Use Regedt32.exe to verify that your performance counter category and your custom performance counter are created in the following registry folder.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

The performance counter category is named MySingleCategory, and the performance counter is named MyCounter.

More Information

Use the Create method of the PerformanceCounterCategory class to create a performance counter category and a single counter at the same time. A performance counter category enables you to group your performance counters. For example, ASP.NET is a performance counter category that contains such performance counters as RequestsCurrent, RequestsQueued, and so on.

Creating Multiple Performance Counters Using CounterCreationDataCollection

If you need to create multiple counters, you can use a CounterCreationDataCollection to programmatically create the custom counter(s) and category. This technique enables you to create the category and multiple counters at the same time.

To create multiple performance counters using CounterCreationDataCollection

  1. Create a new text file named CreateCounters.cs and add the following code.

    CreateCounters.cs
    
    using System;
    using System.Diagnostics;
    
    public class CustomCounters
    {
      public static void Main()
      {
        Console.WriteLine("Creating custom counters");
        CreateCounters();
        Console.WriteLine("Done");
        Console.ReadLine();
      }
    
      public 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.NumberOfItemsHEX32;
    
        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("MyMultipleCategory"))
        {
          PerformanceCounterCategory category = 
          PerformanceCounterCategory.Create("MyMultipleCategory",
          " My New Perf Category Description ", col);
        }
        else
        {
          Console.WriteLine("Counter already exists");
        }
      }
    }
    
  2. Compile the code using the following command line.

    csc.exe /out:CreateCounters.exe /t:exe /r:system.dll CreateCounters.cs
    
  3. Run CreateCounters.exe from a command prompt to create your new performance counters.

    CreateCounters.exe
    

Results

When you run CreateCounters.exe, the following output is produced.

Creating custom counter
Done

Validating Your Performance Counter Category and Your Custom Performance Counters

Use Regedt32.exe to validate that your performance counter category and your custom performance counters are created in the following registry folder.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

MyMultipleCategory is the name of the performance counter category, and Counter1 and Counter2 are the names of the performance counters.

Using Server Explorer

If you have Visual Studio .NET, you can create a custom performance counter manually by using Server Explorer.

To create a custom performance counter with Server Explorer

  1. Open Server Explorer and connect to your local server.
  2. Right-click Performance Counters and select Create New Category.
  3. Enter MyCategory in the category name box and optionally enter a description in the Performance Counter Builder box.
  4. Click New at the bottom of the form and enter MyCounter in the counter name box.
  5. Click OK.

Using Your Performance Counter in Code

Once you have created your custom performance counter, you can use it to instrument your ASP.NET application. You can set a counter's value either by incrementing it with the PerformanceCounter.Increment method or by setting it to a specific value by calling PerformanceCounter.RawValue.

Calling PerformanceCounter.Increment

The following ASP.NET page shows you how to use your custom counter. This code calls PerformanceCounter.Increment to set the new counter value.

IncrementCounter.aspx
<%@ language=C# %>
<%@ import namespace="System.Diagnostics" %>

<script runat=server>

  void IncrementCounter(Object sender, EventArgs e)
  {
    // get an instance of our perf counter
    PerformanceCounter counter = new PerformanceCounter();
    counter.CategoryName = "mySingleCategory";
    counter.CounterName = "myCounter";
    counter.ReadOnly = false;
    
    // increment and close the perf counter
    counter.Increment();
    counter.Close();
    Response.Write("Counter is incremented");
  }

</script>
<form runat=server>
  <input type="submit" id="btnSubmit" Value="Increment Counter"
         OnServerClick="IncrementCounter" runat=server />
</form>

Calling PerformanceCounter.RawValue

The following ASP.NET page shows you how to call PerformanceCounter.RawValue to set your performance counter's value to a specific value.

SetCounter.aspx
<%@ language=C# %>
<%@ import namespace="System.Diagnostics" %>

<script runat=server>
  void SetCounterValue(Object sender, EventArgs e)
  {
    // get an instance of our perf counter
    PerformanceCounter counter = new PerformanceCounter();
    counter.CategoryName = "mySingleCategory";
    counter.CounterName = "myCounter";
    counter.ReadOnly = false;

    long myValue;
    
    if("" != txtCounterValue.Value)
    {
      myValue = Int32.Parse(txtCounterValue.Value);
      // set the value of the counter
      counter.RawValue = myValue;
      counter.Close();
      Response.Write("Counter value is set");
    }
    else
    {
      Response.Write(
         "Enter a numeric value such as 10 for the performance counter");
    }
  }

</script>

<form runat=server>
  <input type="text" id="txtCounterValue"  />
  <input type="submit" id="btnSubmit" Value="Set Counter Value"
         OnServerClick="SetCounterValue" runat=server />
</form>

Monitoring Your Performance Counter

You can monitor your custom performance counter by using Performance Monitor.

To monitor your performance counter

  1. In the Administrative Tools program group, click Performance Monitor.

  2. Add your performance counter to the monitored counters window.

    Your performance counter is listed under MyCategory in the PerformanceObject list.

  3. Start your ASP.NET application and use a browser to access the instrumented page.

  4. Note how Performance Monitor displays the counter value.

Additional Resources

For more information see the following resources:

patterns & practices Developer Center

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

© Microsoft Corporation. All rights reserved.