Export (0) Print
Expand All

PerformanceCounterCategory Class

Represents a performance object, which defines a category of performance counters.

System.Object
  System.Diagnostics.PerformanceCounterCategory

Namespace:  System.Diagnostics
Assembly:  System (in System.dll)

[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	SharedState = true)]
public sealed class PerformanceCounterCategory

The PerformanceCounterCategory type exposes the following members.

  NameDescription
Public methodPerformanceCounterCategory()Initializes a new instance of the PerformanceCounterCategory class, leaves the CategoryName property empty, and sets the MachineName property to the local computer.
Public methodPerformanceCounterCategory(String)Initializes a new instance of the PerformanceCounterCategory class, sets the CategoryName property to the specified value, and sets the MachineName property to the local computer.
Public methodPerformanceCounterCategory(String, String)Initializes a new instance of the PerformanceCounterCategory class and sets the CategoryName and MachineName properties to the specified values.
Top

  NameDescription
Public propertyCategoryHelpGets the category's help text.
Public propertyCategoryNameGets or sets the name of the performance object that defines this category.
Public propertyCategoryTypeGets the performance counter category type.
Public propertyMachineNameGets or sets the name of the computer on which this category exists.
Top

  NameDescription
Public methodCounterExists(String)Determines whether the specified counter is registered to this category, which is indicated by the CategoryName and MachineName properties.
Public methodStatic memberCounterExists(String, String)Determines whether the specified counter is registered to the specified category on the local computer.
Public methodStatic memberCounterExists(String, String, String)Determines whether the specified counter is registered to the specified category on a remote computer.
Public methodStatic memberCreate(String, String, CounterCreationDataCollection) Obsolete. Registers the custom performance counter category containing the specified counters on the local computer.
Public methodStatic memberCreate(String, String, PerformanceCounterCategoryType, CounterCreationDataCollection)Registers the custom performance counter category containing the specified counters on the local computer.
Public methodStatic memberCreate(String, String, String, String) Obsolete. Registers a custom performance counter category containing a single counter of type NumberOfItems32 on the local computer.
Public methodStatic memberCreate(String, String, PerformanceCounterCategoryType, String, String)Registers the custom performance counter category containing a single counter of type NumberOfItems32 on the local computer.
Public methodStatic memberDeleteRemoves the category and its associated counters from the local computer.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public methodStatic memberExists(String)Determines whether the category is registered on the local computer.
Public methodStatic memberExists(String, String)Determines whether the category is registered on the specified computer.
Public methodStatic memberGetCategories()Retrieves a list of the performance counter categories that are registered on the local computer.
Public methodStatic memberGetCategories(String)Retrieves a list of the performance counter categories that are registered on the specified computer.
Public methodGetCounters()Retrieves a list of the counters in a performance counter category that contains exactly one instance.
Public methodGetCounters(String)Retrieves a list of the counters in a performance counter category that contains one or more instances.
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetInstanceNamesRetrieves the list of performance object instances that are associated with this category.
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInstanceExists(String)Determines whether the specified performance object instance exists in the category that is identified by this PerformanceCounterCategory object's CategoryName property.
Public methodStatic memberInstanceExists(String, String)Determines whether a specified category on the local computer contains the specified performance object instance.
Public methodStatic memberInstanceExists(String, String, String)Determines whether a specified category on a specified computer contains the specified performance object instance.
Public methodReadCategoryReads all the counter and performance object instance data that is associated with this performance counter category.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

Important noteImportant

Creating or deleting a performance counter requires synchronization of the underlying code by using a named mutex. If a highly privileged application locks the named mutex, attempts to create or delete a performance counter causes the application to stop responding until the lock is released. To help avoid this problem, never grant UnmanagedCode permission to untrusted code. In addition, UnmanagedCode permission potentially allows other permissions to be bypassed and should only be granted to highly trusted code.

The PerformanceCounterCategory instance's CategoryName property is displayed in the Performance Object field of the Performance Viewer application's Add Counter dialog box.

The PerformanceCounterCategory class provides several methods for interacting with counters and categories on the computer. The Create methods enable you to define custom categories. The Delete method provides a way to remove categories from the computer. The GetCategories method enables you to view the list of categories, while ReadCategory retrieves all the counter and instance data associated with a single category.

A performance counter publishes performance data about an application. Categories include physical components (such as processors, disks, and memory) and system objects (such as processes and threads). System counters that are related to the same performance object are grouped into a category that indicates their common focus. When you create an instance of the PerformanceCounter class, you first indicate the category with which the component will interact, and then you choose a counter from that category.

For example, one Windows counter category is the Memory category. System counters within this category track memory data such as the number of bytes available and the number of bytes cached. If you wanted to work with the bytes cached in your application, you would create an instance of the PerformanceCounter component, connect it to the Memory category, and then pick the appropriate counter (in this case, Cached Bytes) from that category.

Although your system makes many more counter categories available, the categories that you will probably interact with most frequently are the Cache, Memory, Objects, PhysicalDisk, Process, Processor, Server, System, and Thread categories.

Important noteImportant

The RemoveInstance method in the PerformanceCounter class will release the counter and, if the reuse option is selected for that category, the instance of the counter will be reused. This could cause a race condition if another process or even another part of the code is trying to write to the counter instance.

NoteNote

It is strongly recommended that new performance counter categories be created during the installation of the application, not during the execution of the application. This allows time for the operating system to refresh its list of registered performance counter categories. If the list has not been refreshed, the attempt to use the category will fail.

NoteNote

Performance counter categories installed with the .NET Framework 2.0 use separate shared memory, with each performance counter category having its own memory. You can specify the size of separate shared memory by creating a DWORD named FileMappingSize in the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<category name>\Performance. The FileMappingSize value is set to the shared memory size of the category. The default size is 131072 decimal. If the FileMappingSize value is not present, the fileMappingSize attribute value for the performanceCounters element specified in the Machine.config file is used, causing additional overhead for configuration file processing. You can realize a performance improvement for application startup by setting the file mapping size in the registry. For more information about the file mapping size, see <performanceCounters> Element.

NoteNote

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization | SharedState. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

The following code example determines whether a PerformanceCounter and its PerformanceCounterCategory exist on the local computer or on another computer. If these objects do not exist on the local computer, the example optionally creates them. It uses the Exists method to determine whether the PerformanceCounterCategory exists. If the PerformanceCounterCategory does not exist and no counter name is specified, or if the computer is a remote machine, the example exits.

If a PerformanceCounter name is provided, the example uses the CounterExists method and displays the result to the user. If the PerformanceCounter does not exist, the user can delete and re-create the PerformanceCounterCategory with the new PerformanceCounter. If the user does so, the category is deleted using the Delete method.

If requested, the example now creates the new PerformanceCounterCategory and PerformanceCounter using the Create method. If an instance name is specified, the example uses the InstanceExists method and displays the result.

using System;
using System.Diagnostics;
using Microsoft.VisualBasic;

class PerfCounterCatCreateExistMod
{

    public static void Main(string[] args)
    {
        string categoryName = "";
        string counterName = "";
        string instanceName = "";
        string machineName = "";
        string categoryHelp = "";
        string counterHelp = "";
        bool objectExists = false;
        PerformanceCounterCategory pcc;
        bool createCategory = false;

        // Copy the supplied arguments into the local variables. 
        try
        {
            categoryName = args[0];
            counterName = args[1];
            instanceName = args[2];
            machineName = args[3]=="."? "": args[3];
            categoryHelp = args[4];
            counterHelp = args[5];
        }
        catch(Exception ex)
        {
            // Ignore the exception from non-supplied arguments.
        }

        // Verify that the category name is not blank. 
        if (categoryName.Length==0)
        {
            Console.WriteLine("Category name cannot be blank.");
            return;
        }

        // Check whether the specified category exists. 
        if (machineName.Length==0)
        {
            objectExists = PerformanceCounterCategory.Exists(categoryName);

        }
        else
        {
            // Handle the exception that is thrown if the computer  
            // cannot be found. 
            try
            {
                objectExists = PerformanceCounterCategory.Exists(categoryName, machineName);
            }
            catch(Exception ex)
            {
                Console.WriteLine("Error checking for existence of " +
                    "category \"{0}\" on computer \"{1}\":"+"\n" +ex.Message, categoryName, machineName);
                return;
            }
        }

        // Tell the user whether the specified category exists.
        Console.WriteLine("Category \"{0}\" "+ (objectExists? "exists on ": "does not exist on ")+
            (machineName.Length>0? "computer \"{1}\".": "this computer."), categoryName, machineName);

        // If no counter name is given, the program cannot continue. 
        if (counterName.Length==0)
        {
            return;
        }

        // A category can only be created on the local computer. 
        if (!objectExists)
        {
            if (machineName.Length>0)
            {
                return;
            }
            else
            {
                createCategory = true;
            }
        }
        else
        {
            // Check whether the specified counter exists. 
            if (machineName.Length==0)
            {
                objectExists = PerformanceCounterCategory.CounterExists(counterName, categoryName);
            }
            else
            {
                objectExists = PerformanceCounterCategory.CounterExists(counterName, categoryName, machineName);
            }

            // Tell the user whether the counter exists.
            Console.WriteLine("Counter \"{0}\" "+(objectExists? "exists": "does not exist")+
                " in category \"{1}\" on "+(machineName.Length>0? "computer \"{2}\".": "this computer."), 
                counterName, categoryName, machineName);

            // If the counter does not exist, consider creating it. 
            if (!objectExists)

                // If this is a remote computer,  
                // exit because the category cannot be created.
            {
                if (machineName.Length>0)
                {
                    return;
                }
                else
                {
                    // Ask whether the user wants to recreate the category.
                    Console.Write("Do you want to delete and recreate " +
                        "category \"{0}\" with your new counter? [Y/N]: ", categoryName);
                    string userReply = Console.ReadLine();

                    // If yes, delete the category so it can be recreated later. 
                    if (userReply.Trim().ToUpper()=="Y")
                    {
                        PerformanceCounterCategory.Delete(categoryName);
                        createCategory = true;
                    }
                    else
                    {
                        return;
                    }
                }
            }
        }

        // Create the category if it was deleted or it never existed. 
        if (createCategory)
        {
            pcc = PerformanceCounterCategory.Create(categoryName, categoryHelp, counterName, counterHelp);

            Console.WriteLine("Category \"{0}\" with counter \"{1}\" created.", pcc.CategoryName, counterName);

        }
        else if(instanceName.Length>0)
        {
            if (machineName.Length==0)
            {
                objectExists = PerformanceCounterCategory.InstanceExists(instanceName, categoryName);
            }
            else
            {
                objectExists = PerformanceCounterCategory.InstanceExists(instanceName, categoryName, machineName);
            }

            // Tell the user whether the instance exists.
            Console.WriteLine("Instance \"{0}\" "+(objectExists? "exists": "does not exist")+
                " in category \"{1}\" on " + (machineName.Length>0? "computer \"{2}\".": "this computer."), 
                instanceName, categoryName, machineName);
        }
    }
}

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft