How Do I...Write to a performance counter?

Windows performance counters allow your applications and components to publish, capture, and analyze the performance data that applications, services, and drivers provide. You can use this information to determine system bottlenecks, and fine-tune system and application performance. For example, you might use a performance counter to track the number of orders processed per second or the number of users currently connected to the system. Using the common language runtime's PerformanceCounter component, you can easily create your own custom counters and publish performance data relevant to your application, such as those mentioned above.

This sample illustrates publishing (writing) simple performance information to a custom performance counter. It's a small console application that can be run from a command prompt. The application takes three command line arguments. The first is a performance object name (category). The second argument is the counter name. The third argument is the counter instance name.

This example shows how to publish data about the total number of international orders for milk. The object name and counter name are "Orders" and "Milk Orders" respectively. To run the sample the object has to be installed first with the install switch, as follow:

> PCWrite  /inst

After the object has been successfully installed, run the app with no switch, as follows:

> PCWrite
Now, wait for the application to display Started and run the PerfMon.exe. In PerfMon, click on the add toolbar button. A dialog will open. Select the Orders performance object, Milk Orders counter, and International instance. Click Add, close the dialog, and observe that you can use the PCWrite sample to change the published value by pressing + or -.

In its simplest form, writing to a custom performance counter involves:

  1. Instantiating a PerformanceCounter component and pointing it to an appropriate performance counter:

    
    Dim objectName As String = "Orders"
    Dim counterName As String = "Milk Orders"
    Dim instanceName As String = "International"
    
    Dim counter As PerformanceCounter
    counter = New PerformanceCounter(objectName, counterName, instanceName)
    
    VB

  2. Setting the RawValue property of the counter:

    
    counter.RawValue = 50
    
    VB

The "Orders" object that was created could be deleted with a delete switch, as follows:

> PCWrite /del

Example

 
VB PCWrite.exe

[Run Sample] | [View Source]


Copyright 2001-2002 Microsoft Corporation. All rights reserved.