如何:添加和移除性能计数器实例

更新:2007 年 11 月

使用计数器和类别时,可以动态地添加和移除实例。例如,可以为基于 Web 的零售应用程序的每个用户添加一个实例,这样就可以跟踪关于其操作的信息,然后在用户会话过期后移除该实例。

可以通过设置计数器的原始值来添加实例。如果没有与该计数器对应的实例存在,首次设置 RawValue 属性时将创建一个实例;如果没有指定其他实例,将认为对原始值的所有后续操作都会影响到该实例。通过指定一个新的实例名称并在其后设置一个值,可以创建更多实例。

说明:

实例是在设置实例值的过程(而不是指定新实例的名称的过程)中创建的。

计数器不能添加到现有的类别中,除非是作为类别创建的一部分,而实例则可以随时在用户定义的类别中添加和移除。可以使用 InstanceName 属性在实例之间切换。

可以使用 RemoveInstance 方法将自定义性能计数器的实例从内存中移除。例如,假设您有一个基于 Web 的零售应用程序,它使用名为 OrderInProgress 的类别,在该类别中维护着每个用户当前购物车的实例。当用户首次向购物车中添加项时,应用程序为该用户创建一个新实例。当用户完成订购时,应用程序删除该实例。在订购过程中,您用计数器(如 NumberofItemsinCart、TimeSinceCreation 和 NumberofItemsAddedPerSecond)更新该实例。

不能从性能计数器中移除作为 Windows 默认组成部分的实例。如果 PerformanceCounter 组件未引用有效的实例,此方法将引发异常。

说明:

Microsoft Windows NT 4.0 版不完全支持 PerformanceCounter 类。您可从系统计数器中读取,但不能创建、写入或删除自定义计数器。

添加性能计数器实例

  1. 以常规方式创建类别和计数器。有关更多信息,请参见 如何:创建性能计数器类别

  2. InstanceName 属性设置为该实例的唯一名称,然后设置该实例的 RawValue 属性。

    以下代码显示如何创建一个现有性能计数器类别的数个实例:

    ' Assumes the category and counter have already been created.
    Dim myCounter As New System.Diagnostics.PerformanceCounter( _
       "cat", "counter", "instance1", False)
    ' Set the raw value to automatically create instance1.
    myCounter.RawValue = 100
    ' State that you will now be working with a different instance.
    myCounter.InstanceName = "instance2"
    ' Setting the value actually creates instance2.
    myCounter.RawValue = 200
    
         // Assumes category and counter have been created.
            System.Diagnostics.PerformanceCounter myCounter =
               new System.Diagnostics.PerformanceCounter(
               "cat", "counter", "instance1", false);
            // Set the raw value to automatically create instance1.
            myCounter.RawValue = 100;
            // State that you will now be working with a different instance.
            myCounter.InstanceName = "instance2";
            // Setting the value actually creates instance2.
            myCounter.RawValue = 200;
    
    

移除性能计数器实例

  1. 创建 PerformanceCounter 组件的一个实例,该实例连接到您要从中移除实例的计数器。有关更多信息,请参见 如何:创建 PerformanceCounter 组件实例

  2. InstanceName 属性设置为要删除的实例。

  3. 调用组件的 RemoveInstance 方法。

    下面的示例显示如何从计数器中移除名为 Reference 的实例:

    ' Assumes that you have configured PerformanceCounter1 to
    ' interact with the appropriate counter.
    PerformanceCounter1.InstanceName = "Reference"
    PerformanceCounter1.RemoveInstance()
    
         // Assumes that you have configured PerformanceCounter1 to
            // interact with the appropriate counter.
            PerformanceCounter1.InstanceName = "Reference";
            PerformanceCounter1.RemoveInstance();
    

请参见

任务

如何:创建 PerformanceCounter 组件实例

概念

类别和计数器管理