Editar

Partilhar via


PerformanceCounterCategory Class

Definition

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

public ref class PerformanceCounterCategory sealed
public sealed class PerformanceCounterCategory
type PerformanceCounterCategory = class
Public NotInheritable Class PerformanceCounterCategory
Inheritance
PerformanceCounterCategory

Examples

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);
        }
    }
}
Imports System.Diagnostics

Module PerfCounterCatCreateExistMod

    Sub Main(ByVal args() As String)
        Dim categoryName As String = ""
        Dim counterName As String = ""
        Dim instanceName As String = ""
        Dim machineName As String = ""
        Dim categoryHelp As String = ""
        Dim counterHelp As String = ""
        Dim objectExists As Boolean = False
        Dim pcc As PerformanceCounterCategory
        Dim createCategory As Boolean = False

        ' Copy the supplied arguments into the local variables.
        Try
            categoryName = args(0)
            counterName = args(1)
            instanceName = args(2)
            machineName = IIf(args(3) = ".", "", args(3))
            categoryHelp = args(4)
            counterHelp = args(5)
        Catch ex As Exception
            ' Ignore the exception from non-supplied arguments.
        End Try

        ' Verify that the category name is not blank.
        If categoryName.Length = 0 Then
            Console.WriteLine("Category name cannot be blank.")
            Return
        End If

        ' Check whether the specified category exists.
        If machineName.Length = 0 Then
            objectExists = _
                PerformanceCounterCategory.Exists(categoryName)

        Else
            ' Handle the exception that is thrown if the computer 
            ' cannot be found.
            Try
                objectExists = PerformanceCounterCategory.Exists( _
                    categoryName, machineName)
            Catch ex As Exception
                Console.WriteLine("Error checking for existence of " & _
                    "category ""{0}"" on computer ""{1}"":" & vbCrLf & _
                    ex.Message, categoryName, machineName)
                Return
            End Try
        End If

        ' Tell the user whether the specified category exists.
        Console.WriteLine("Category ""{0}"" " & _
            IIf(objectExists, "exists on ", "does not exist on ") & _
            IIf(machineName.Length > 0, _
                "computer ""{1}"".", "this computer."), _
            categoryName, machineName)

        ' If no counter name is given, the program cannot continue.
        If counterName.Length = 0 Then
            Return
        End If

        ' A category can only be created on the local computer.
        If Not objectExists Then
            If machineName.Length > 0 Then
                Return
            Else
                createCategory = True
            End If
        Else
            ' Check whether the specified counter exists.
            If machineName.Length = 0 Then
                objectExists = PerformanceCounterCategory.CounterExists( _
                    counterName, categoryName)
            Else
                objectExists = PerformanceCounterCategory.CounterExists( _
                    counterName, categoryName, machineName)
            End If

            ' Tell the user whether the counter exists.
            Console.WriteLine("Counter ""{0}"" " & _
                IIf(objectExists, "exists", "does not exist") & _
                " in category ""{1}"" on " & _
                IIf(machineName.Length > 0, _
                    "computer ""{2}"".", "this computer."), _
                counterName, categoryName, machineName)

            ' If the counter does not exist, consider creating it.
            If Not objectExists Then

                ' If this is a remote computer, 
                ' exit because the category cannot be created.
                If machineName.Length > 0 Then
                    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)
                    Dim userReply As String = Console.ReadLine()

                    ' If yes, delete the category so it can be recreated later.
                    If userReply.Trim.ToUpper.Chars(0) = "Y" Then
                        PerformanceCounterCategory.Delete(categoryName)
                        createCategory = True
                    Else
                        Return
                    End If
                End If
            End If
        End If

        ' Create the category if it was deleted or it never existed.
        If createCategory Then
            pcc = PerformanceCounterCategory.Create( _
                categoryName, categoryHelp, counterName, counterHelp)

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

        ElseIf instanceName.Length > 0 Then

            ' If an instance name was given, check whether it exists.
            If machineName.Length = 0 Then
                objectExists = PerformanceCounterCategory.InstanceExists( _
                    instanceName, categoryName)
            Else
                objectExists = PerformanceCounterCategory.InstanceExists( _
                    instanceName, categoryName, machineName)
            End If

            ' Tell the user whether the instance exists.
            Console.WriteLine("Instance ""{0}"" " & _
                IIf(objectExists, "exists", "does not exist") & _
                " in category ""{1}"" on " & _
                IIf(machineName.Length > 0, _
                    "computer ""{2}"".", "this computer."), _
                instanceName, categoryName, machineName)
        End If
    End Sub
End Module

Remarks

Important

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

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.

Note

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.

Note

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>.

Constructors

PerformanceCounterCategory()

Initializes a new instance of the PerformanceCounterCategory class, leaves the CategoryName property empty, and sets the MachineName property to the local computer.

PerformanceCounterCategory(String, String)

Initializes a new instance of the PerformanceCounterCategory class and sets the CategoryName and MachineName properties to the specified values.

PerformanceCounterCategory(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.

Properties

CategoryHelp

Gets the category's help text.

CategoryName

Gets or sets the name of the performance object that defines this category.

CategoryType

Gets the performance counter category type.

MachineName

Gets or sets the name of the computer on which this category exists.

Methods

CounterExists(String, String, String)

Determines whether the specified counter is registered to the specified category on a remote computer.

CounterExists(String, String)

Determines whether the specified counter is registered to the specified category on the local computer.

CounterExists(String)

Determines whether the specified counter is registered to this category, which is indicated by the CategoryName and MachineName properties.

Create(String, String, CounterCreationDataCollection)
Obsolete.
Obsolete.
Obsolete.

Registers the custom performance counter category containing the specified counters on the local computer.

Create(String, String, PerformanceCounterCategoryType, CounterCreationDataCollection)

Registers the custom performance counter category containing the specified counters on the local computer.

Create(String, String, PerformanceCounterCategoryType, String, String)

Registers the custom performance counter category containing a single counter of type NumberOfItems32 on the local computer.

Create(String, String, String, String)
Obsolete.
Obsolete.
Obsolete.

Registers a custom performance counter category containing a single counter of type NumberOfItems32 on the local computer.

Delete(String)

Removes the category and its associated counters from the local computer.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Exists(String, String)

Determines whether the category is registered on the specified computer.

Exists(String)

Determines whether the category is registered on the local computer.

GetCategories()

Retrieves a list of the performance counter categories that are registered on the local computer.

GetCategories(String)

Retrieves a list of the performance counter categories that are registered on the specified computer.

GetCounters()

Retrieves a list of the counters in a performance counter category that contains exactly one instance.

GetCounters(String)

Retrieves a list of the counters in a performance counter category that contains one or more instances.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetInstanceNames()

Retrieves the list of performance object instances that are associated with this category.

GetType()

Gets the Type of the current instance.

(Inherited from Object)
InstanceExists(String, String, String)

Determines whether a specified category on a specified computer contains the specified performance object instance.

InstanceExists(String, String)

Determines whether a specified category on the local computer contains the specified performance object instance.

InstanceExists(String)

Determines whether the specified performance object instance exists in the category that is identified by this PerformanceCounterCategory object's CategoryName property.

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ReadCategory()

Reads all the counter and performance object instance data that is associated with this performance counter category.

ToString()

Returns a string that represents the current object.

(Inherited from Object)

Applies to

See also