PerformanceCounterCategory 类

定义

表示性能对象,它定义性能计数器的类别。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
继承
PerformanceCounterCategory

示例

下面的代码示例将确定是否 PerformanceCounter PerformanceCounterCategory 存在于本地计算机上或另一台计算机上。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. 它使用 Exists 方法来确定是否 PerformanceCounterCategory 存在。It uses the Exists method to determine whether the PerformanceCounterCategory exists. 如果不 PerformanceCounterCategory 存在并且未指定计数器名称,或者计算机是远程计算机,则此示例将退出。If the PerformanceCounterCategory does not exist and no counter name is specified, or if the computer is a remote machine, the example exits.

如果 PerformanceCounter 提供了名称,该示例将使用 CounterExists 方法并向用户显示结果。If a PerformanceCounter name is provided, the example uses the CounterExists method and displays the result to the user. 如果不 PerformanceCounter 存在,则用户可以删除并重新创建 PerformanceCounterCategory 新的 PerformanceCounterIf the PerformanceCounter does not exist, the user can delete and re-create the PerformanceCounterCategory with the new PerformanceCounter. 如果用户这样做,则使用方法删除类别 DeleteIf the user does so, the category is deleted using the Delete method.

如果请求,则该示例现在使用方法创建新的 PerformanceCounterCategoryPerformanceCounter 使用 Create 方法。If requested, the example now creates the new PerformanceCounterCategory and PerformanceCounter using the Create method. 如果指定了实例名称,则此示例将使用 InstanceExists 方法并显示结果。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

注解

重要

创建或删除性能计数器需要使用已命名的 mutex 同步基础代码。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. 若要避免此问题,请不要向 UnmanagedCode 不受信任的代码授予权限。To help avoid this problem, never grant UnmanagedCode permission to untrusted code. 此外, UnmanagedCode 权限可能会允许绕过其他权限,只应授予高度受信任的代码。In addition, UnmanagedCode permission potentially allows other permissions to be bypassed and should only be granted to highly trusted code.

PerformanceCounterCategory实例的 CategoryName 属性将显示在 "性能查看器" 应用程序的 "添加计数器" 对话框的 "性能对象" 字段中。The PerformanceCounterCategory instance's CategoryName property is displayed in the Performance Object field of the Performance Viewer application's Add Counter dialog box.

PerformanceCounterCategory类提供若干方法,用于与计算机上的计数器和类别交互。The PerformanceCounterCategory class provides several methods for interacting with counters and categories on the computer. 使用 Create 方法可以定义自定义类别。The Create methods enable you to define custom categories. Delete方法提供了一种从计算机中删除类别的方法。The Delete method provides a way to remove categories from the computer. GetCategories使用方法可以查看类别列表,同时 ReadCategory 检索与单个类别关联的所有计数器和实例数据。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. 当您创建类的实例时 PerformanceCounter ,您首先指示组件将与之交互的类别,然后从该类别中选择一个计数器。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.

例如,一个 Windows 计数器类别为内存类别。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. 如果要处理缓存在应用程序中的字节,则需创建组件的实例 PerformanceCounter ,将其连接到内存类别,然后选择相应的计数器 (在本例中,从该类别缓存的字节) 。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.

尽管你的系统提供了更多的计数器类别,但你可能会经常与之交互的类别包括缓存、内存、对象、PhysicalDisk、进程、处理器、服务器、系统和线程类别。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.

重要

RemoveInstance类中的方法 PerformanceCounter 将释放计数器,并且如果为该类别选择了 "重复使用" 选项,则会重复使用计数器的实例。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.

备注

强烈建议在安装应用程序期间(而不是在应用程序执行期间)创建新的性能计数器类别。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.

备注

随一起安装的性能计数器类别 .NET Framework 2.0.NET Framework 2.0 使用单独的共享内存,每个性能计数器类别都有自己的内存。Performance counter categories installed with the .NET Framework 2.0.NET Framework 2.0 use separate shared memory, with each performance counter category having its own memory. 可以通过在注册表项 HKEY_LOCAL_MACHINE \SYSTEM\CurrentControlSet\Services \Performance. 中创建一个名为 FileMappingSize 的 DWORD 来指定单独共享内存的大小。 \ <category name>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. FileMappingSize 值设置为类别的共享内存大小。The FileMappingSize value is set to the shared memory size of the category. 默认大小为131072。The default size is 131072 decimal. 如果 FileMappingSize 值不存在,则 fileMappingSize performanceCounters 使用 Machine.config 文件中指定的元素的属性值,从而导致配置文件处理出现额外的开销。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. 有关文件映射大小的详细信息,请参阅 < performanceCounters > For more information about the file mapping size, see <performanceCounters>.

构造函数

PerformanceCounterCategory()

初始化 PerformanceCounterCategory 类的新实例,让 CategoryName 属性保持为空,并将 MachineName 属性设置为本地计算机。Initializes a new instance of the PerformanceCounterCategory class, leaves the CategoryName property empty, and sets the MachineName property to the local computer.

PerformanceCounterCategory(String)

初始化 PerformanceCounterCategory 类的新实例,将 CategoryName 属性设置为指定的值,并将 MachineName 属性设置为本地计算机。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.

PerformanceCounterCategory(String, String)

初始化 PerformanceCounterCategory 类的新实例,并将 CategoryNameMachineName 属性设置为指定的值。Initializes a new instance of the PerformanceCounterCategory class and sets the CategoryName and MachineName properties to the specified values.

属性

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.

方法

CounterExists(String)

确定是否向此类别注册了指定的计数器,这由 CategoryNameMachineName 属性指示。Determines whether the specified counter is registered to this category, which is indicated by the CategoryName and MachineName properties.

CounterExists(String, String)

确定是否向本地计算机上的指定类别注册了指定的计数器。Determines whether the specified counter is registered to the specified category on the local computer.

CounterExists(String, String, String)

确定是否向远程计算机上的指定类别注册了指定的计数器。Determines whether the specified counter is registered to the specified category on a remote computer.

Create(String, String, CounterCreationDataCollection)
已过时。
已过时。
已过时。

在本地计算机上注册包含指定计数器的自定义性能计数器类别。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)

在本地计算机上注册包含 NumberOfItems32 类型的单个计数器的自定义性能计数器类别。Registers the custom performance counter category containing a single counter of type NumberOfItems32 on the local computer.

Create(String, String, String, String)
已过时。
已过时。
已过时。

在本地计算机上注册包含 NumberOfItems32 类型的单个计数器的自定义性能计数器类别。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.

(继承自 Object)
Exists(String)

确定是否在本地计算机上注册了该类别。Determines whether the category is registered on the local computer.

Exists(String, String)

确定是否在指定的计算机上注册了该类别。Determines whether the category is registered on the specified 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.

(继承自 Object)
GetInstanceNames()

检索与此类别关联的性能对象实例列表。Retrieves the list of performance object instances that are associated with this category.

GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
InstanceExists(String)

确定由此 PerformanceCounterCategory 对象的 CategoryName 属性标识的类别中是否存在指定的性能对象实例。Determines whether the specified performance object instance exists in the category that is identified by this PerformanceCounterCategory object's CategoryName property.

InstanceExists(String, String)

确定本地计算机上指定的类别是否包含指定的性能对象实例。Determines whether a specified category on the local computer contains the specified performance object instance.

InstanceExists(String, String, String)

确定指定计算机上的指定类别是否包含指定的性能对象实例。Determines whether a specified category on a specified computer contains the specified performance object instance.

MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 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.

(继承自 Object)

适用于

另请参阅