PerformanceCounter PerformanceCounter PerformanceCounter PerformanceCounter Class

定义

表示 Windows NT 性能计数器组件。Represents a Windows NT performance counter component.

public ref class PerformanceCounter sealed : System::ComponentModel::Component, System::ComponentModel::ISupportInitialize
public sealed class PerformanceCounter : System.ComponentModel.Component, System.ComponentModel.ISupportInitialize
type PerformanceCounter = class
    inherit Component
    interface ISupportInitialize
Public NotInheritable Class PerformanceCounter
Inherits Component
Implements ISupportInitialize
继承
实现

示例

下面的代码示例演示如何将PerformanceCounter类来创建和使用AverageCount64计数器类型。The following code example demonstrates the use of the PerformanceCounter class to create and use an AverageCount64 counter type. 该示例创建类别、 计数器设置、 从该计数器,并调用收集数据CounterSampleCalculator类来解释性能计数器数据。The example creates categories, sets up counters, collects data from the counters, and calls the CounterSampleCalculator class to interpret the performance counter data. 在控制台窗口中显示的中间和最后一个结果。The intermediate and final results are displayed in the console window. 其他性能计数器类型的其他示例,请参阅PerformanceCounterType枚举。For additional examples of other performance counter types, see the PerformanceCounterType enumeration.

#using <System.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Collections::Specialized;
using namespace System::Diagnostics;

// Output information about the counter sample.
void OutputSample( CounterSample s )
{
   Console::WriteLine( "\r\n+++++++++++" );
   Console::WriteLine( "Sample values - \r\n" );
   Console::WriteLine( "   BaseValue        = {0}", s.BaseValue );
   Console::WriteLine( "   CounterFrequency = {0}", s.CounterFrequency );
   Console::WriteLine( "   CounterTimeStamp = {0}", s.CounterTimeStamp );
   Console::WriteLine( "   CounterType      = {0}", s.CounterType );
   Console::WriteLine( "   RawValue         = {0}", s.RawValue );
   Console::WriteLine( "   SystemFrequency  = {0}", s.SystemFrequency );
   Console::WriteLine( "   TimeStamp        = {0}", s.TimeStamp );
   Console::WriteLine( "   TimeStamp100nSec = {0}", s.TimeStamp100nSec );
   Console::WriteLine( "++++++++++++++++++++++" );
}

//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
//    Description - This counter type shows how many items are processed, on average,
//        during an operation. Counters of this type display a ratio of the items 
//        processed (such as bytes sent) to the number of operations completed. The  
//        ratio is calculated by comparing the number of items processed during the 
//        last interval to the number of operations completed during the last interval. 
// Generic type - Average
//      Formula - (N1 - N0) / (D1 - D0), where the numerator (N) represents the number 
//        of items processed during the last sample interval and the denominator (D) 
//        represents the number of operations completed during the last two sample 
//        intervals. 
//    Average (Nx - N0) / (Dx - D0)  
//    Example PhysicalDisk\ Avg. Disk Bytes/Transfer 
//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
float MyComputeCounterValue( CounterSample s0, CounterSample s1 )
{
   float numerator = (float)s1.RawValue - (float)s0.RawValue;
   float denomenator = (float)s1.BaseValue - (float)s0.BaseValue;
   float counterValue = numerator / denomenator;
   return counterValue;
}

bool SetupCategory()
{
   if (  !PerformanceCounterCategory::Exists( "AverageCounter64SampleCategory" ) )
   {
      CounterCreationDataCollection^ CCDC = gcnew CounterCreationDataCollection;
      
      // Add the counter.
      CounterCreationData^ averageCount64 = gcnew CounterCreationData;
      averageCount64->CounterType = PerformanceCounterType::AverageCount64;
      averageCount64->CounterName = "AverageCounter64Sample";
      CCDC->Add( averageCount64 );
      
      // Add the base counter.
      CounterCreationData^ averageCount64Base = gcnew CounterCreationData;
      averageCount64Base->CounterType = PerformanceCounterType::AverageBase;
      averageCount64Base->CounterName = "AverageCounter64SampleBase";
      CCDC->Add( averageCount64Base );
      
      // Create the category.
      PerformanceCounterCategory::Create( "AverageCounter64SampleCategory", "Demonstrates usage of the AverageCounter64 performance counter type.", CCDC );
      return (true);
   }
   else
   {
      Console::WriteLine( "Category exists - AverageCounter64SampleCategory" );
      return (false);
   }
}

void CreateCounters( PerformanceCounter^% PC, PerformanceCounter^% BPC )
{
   
   // Create the counters.
   PC = gcnew PerformanceCounter( "AverageCounter64SampleCategory","AverageCounter64Sample",false );

   BPC = gcnew PerformanceCounter( "AverageCounter64SampleCategory","AverageCounter64SampleBase",false );
   PC->RawValue = 0;
   BPC->RawValue = 0;
}
void CollectSamples( ArrayList^ samplesList, PerformanceCounter^ PC, PerformanceCounter^ BPC )
{
   Random^ r = gcnew Random( DateTime::Now.Millisecond );

   // Loop for the samples.
   for ( int j = 0; j < 100; j++ )
   {
      int value = r->Next( 1, 10 );
      Console::Write( "{0} = {1}", j, value );
      PC->IncrementBy( value );
      BPC->Increment();
      if ( (j % 10) == 9 )
      {
         OutputSample( PC->NextSample() );
         samplesList->Add( PC->NextSample() );
      }
      else
            Console::WriteLine();
      System::Threading::Thread::Sleep( 50 );
   }
}

void CalculateResults( ArrayList^ samplesList )
{
   for ( int i = 0; i < (samplesList->Count - 1); i++ )
   {
      // Output the sample.
      OutputSample(  *safe_cast<CounterSample^>(samplesList[ i ]) );
      OutputSample(  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) );
      
      // Use .NET to calculate the counter value.
      Console::WriteLine( ".NET computed counter value = {0}", CounterSampleCalculator::ComputeCounterValue(  *safe_cast<CounterSample^>(samplesList[ i ]),  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) ) );
      
      // Calculate the counter value manually.
      Console::WriteLine( "My computed counter value = {0}", MyComputeCounterValue(  *safe_cast<CounterSample^>(samplesList[ i ]),  *safe_cast<CounterSample^>(samplesList[ i + 1 ]) ) );
   }
}

int main()
{
   ArrayList^ samplesList = gcnew ArrayList;
   PerformanceCounter^ PC;
   PerformanceCounter^ BPC;
   SetupCategory();
   CreateCounters( PC, BPC );
   CollectSamples( samplesList, PC, BPC );
   CalculateResults( samplesList );
}

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;

public class App {

    private static PerformanceCounter avgCounter64Sample;
    private static PerformanceCounter avgCounter64SampleBase;

    public static void Main()
    {
    
        ArrayList samplesList = new ArrayList();

        // If the category does not exist, create the category and exit.
        // Performance counters should not be created and immediately used.
        // There is a latency time to enable the counters, they should be created
        // prior to executing the application that uses the counters.
        // Execute this sample a second time to use the category.
        if (SetupCategory())
            return;
        CreateCounters();
        CollectSamples(samplesList);
        CalculateResults(samplesList);

    }

    private static bool SetupCategory()
    {
        if ( !PerformanceCounterCategory.Exists("AverageCounter64SampleCategory") ) 
        {

            CounterCreationDataCollection counterDataCollection = new CounterCreationDataCollection();

            // Add the counter.
            CounterCreationData averageCount64 = new CounterCreationData();
            averageCount64.CounterType = PerformanceCounterType.AverageCount64;
            averageCount64.CounterName = "AverageCounter64Sample";
            counterDataCollection.Add(averageCount64);

            // Add the base counter.
            CounterCreationData averageCount64Base = new CounterCreationData();
            averageCount64Base.CounterType = PerformanceCounterType.AverageBase;
            averageCount64Base.CounterName = "AverageCounter64SampleBase";
            counterDataCollection.Add(averageCount64Base);

            // Create the category.
            PerformanceCounterCategory.Create("AverageCounter64SampleCategory",
                "Demonstrates usage of the AverageCounter64 performance counter type.",
                PerformanceCounterCategoryType.SingleInstance, counterDataCollection);

            return(true);
        }
        else
        {
            Console.WriteLine("Category exists - AverageCounter64SampleCategory");
            return(false);
        }
    }

    private static void CreateCounters()
    {
        // Create the counters.

        avgCounter64Sample = new PerformanceCounter("AverageCounter64SampleCategory", 
            "AverageCounter64Sample", 
            false);


        avgCounter64SampleBase = new PerformanceCounter("AverageCounter64SampleCategory", 
            "AverageCounter64SampleBase", 
            false);

        avgCounter64Sample.RawValue=0;
        avgCounter64SampleBase.RawValue=0;
    }
    private static void CollectSamples(ArrayList samplesList)
    {

        Random r = new Random( DateTime.Now.Millisecond );

        // Loop for the samples.
        for (int j = 0; j < 100; j++) 
        {

            int value = r.Next(1, 10);
            Console.Write(j + " = " + value);

            avgCounter64Sample.IncrementBy(value);

            avgCounter64SampleBase.Increment();

            if ((j % 10) == 9) 
            {
                OutputSample(avgCounter64Sample.NextSample());
                samplesList.Add( avgCounter64Sample.NextSample() );
            }
            else
                Console.WriteLine();

            System.Threading.Thread.Sleep(50);
        }

    }

    private static void CalculateResults(ArrayList samplesList)
    {
        for(int i = 0; i < (samplesList.Count - 1); i++)
        {
            // Output the sample.
            OutputSample( (CounterSample)samplesList[i] );
            OutputSample( (CounterSample)samplesList[i+1] );

            // Use .NET to calculate the counter value.
            Console.WriteLine(".NET computed counter value = " +
                CounterSampleCalculator.ComputeCounterValue((CounterSample)samplesList[i],
                (CounterSample)samplesList[i+1]) );

            // Calculate the counter value manually.
            Console.WriteLine("My computed counter value = " + 
                MyComputeCounterValue((CounterSample)samplesList[i],
                (CounterSample)samplesList[i+1]) );

        }
    }

    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    //    Description - This counter type shows how many items are processed, on average,
    //        during an operation. Counters of this type display a ratio of the items 
    //        processed (such as bytes sent) to the number of operations completed. The  
    //        ratio is calculated by comparing the number of items processed during the 
    //        last interval to the number of operations completed during the last interval. 
    // Generic type - Average
    //      Formula - (N1 - N0) / (D1 - D0), where the numerator (N) represents the number 
    //        of items processed during the last sample interval and the denominator (D) 
    //        represents the number of operations completed during the last two sample 
    //        intervals. 
    //    Average (Nx - N0) / (Dx - D0)  
    //    Example PhysicalDisk\ Avg. Disk Bytes/Transfer 
    //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1)
    {
        Single numerator = (Single)s1.RawValue - (Single)s0.RawValue;
        Single denomenator = (Single)s1.BaseValue - (Single)s0.BaseValue;
        Single counterValue = numerator / denomenator;
        return(counterValue);
    }

    // Output information about the counter sample.
    private static void OutputSample(CounterSample s)
    {
        Console.WriteLine("\r\n+++++++++++");
        Console.WriteLine("Sample values - \r\n");
        Console.WriteLine("   BaseValue        = " + s.BaseValue);
        Console.WriteLine("   CounterFrequency = " + s.CounterFrequency);
        Console.WriteLine("   CounterTimeStamp = " + s.CounterTimeStamp);
        Console.WriteLine("   CounterType      = " + s.CounterType);
        Console.WriteLine("   RawValue         = " + s.RawValue);
        Console.WriteLine("   SystemFrequency  = " + s.SystemFrequency);
        Console.WriteLine("   TimeStamp        = " + s.TimeStamp);
        Console.WriteLine("   TimeStamp100nSec = " + s.TimeStamp100nSec);
        Console.WriteLine("++++++++++++++++++++++");
    }
}
Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Diagnostics

 _

Public Class App

    Private Shared avgCounter64Sample As PerformanceCounter
    Private Shared avgCounter64SampleBase As PerformanceCounter


    Public Shared Sub Main()

        Dim samplesList As New ArrayList()
        'If the category does not exist, create the category and exit.
        'Performance counters should not be created and immediately used.
        'There is a latency time to enable the counters, they should be created
        'prior to executing the application that uses the counters.
        'Execute this sample a second time to use the counters.
        If Not (SetupCategory()) Then
            CreateCounters()
            CollectSamples(samplesList)
            CalculateResults(samplesList)
        End If

    End Sub 'Main

    Private Shared Function SetupCategory() As Boolean
        If Not PerformanceCounterCategory.Exists("AverageCounter64SampleCategory") Then

            Dim counterDataCollection As New CounterCreationDataCollection()

            ' Add the counter.
            Dim averageCount64 As New CounterCreationData()
            averageCount64.CounterType = PerformanceCounterType.AverageCount64
            averageCount64.CounterName = "AverageCounter64Sample"
            counterDataCollection.Add(averageCount64)

            ' Add the base counter.
            Dim averageCount64Base As New CounterCreationData()
            averageCount64Base.CounterType = PerformanceCounterType.AverageBase
            averageCount64Base.CounterName = "AverageCounter64SampleBase"
            counterDataCollection.Add(averageCount64Base)

            ' Create the category.
            PerformanceCounterCategory.Create("AverageCounter64SampleCategory", _
               "Demonstrates usage of the AverageCounter64 performance counter type.", _
                      PerformanceCounterCategoryType.SingleInstance, counterDataCollection)

            Return True
        Else
            Console.WriteLine("Category exists - AverageCounter64SampleCategory")
            Return False
        End If
    End Function 'SetupCategory

    Private Shared Sub CreateCounters()
        ' Create the counters.

        avgCounter64Sample = New PerformanceCounter("AverageCounter64SampleCategory", "AverageCounter64Sample", False)

        avgCounter64SampleBase = New PerformanceCounter("AverageCounter64SampleCategory", "AverageCounter64SampleBase", False)

        avgCounter64Sample.RawValue = 0
        avgCounter64SampleBase.RawValue = 0
    End Sub 'CreateCounters

    Private Shared Sub CollectSamples(ByVal samplesList As ArrayList)

        Dim r As New Random(DateTime.Now.Millisecond)

        ' Loop for the samples.
        Dim j As Integer
        For j = 0 To 99

            Dim value As Integer = r.Next(1, 10)
            Console.Write(j.ToString() + " = " + value.ToString())

            avgCounter64Sample.IncrementBy(value)

            avgCounter64SampleBase.Increment()

            If j Mod 10 = 9 Then
                OutputSample(avgCounter64Sample.NextSample())
                samplesList.Add(avgCounter64Sample.NextSample())
            Else
                Console.WriteLine()
            End If
            System.Threading.Thread.Sleep(50)
        Next j
    End Sub 'CollectSamples

    Private Shared Sub CalculateResults(ByVal samplesList As ArrayList)
        Dim i As Integer
        For i = 0 To (samplesList.Count - 1) - 1
            ' Output the sample.
            OutputSample(CType(samplesList(i), CounterSample))
            OutputSample(CType(samplesList((i + 1)), CounterSample))

            ' Use .NET to calculate the counter value.
            Console.WriteLine(".NET computed counter value = " + CounterSampleCalculator.ComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)).ToString())

            ' Calculate the counter value manually.
            Console.WriteLine("My computed counter value = " + MyComputeCounterValue(CType(samplesList(i), CounterSample), CType(samplesList((i + 1)), CounterSample)).ToString())
        Next i
    End Sub 'CalculateResults

    '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    '	Description - This counter type shows how many items are processed, on average,
    '		during an operation. Counters of this type display a ratio of the items 
    '		processed (such as bytes sent) to the number of operations completed. The  
    '		ratio is calculated by comparing the number of items processed during the 
    '		last interval to the number of operations completed during the last interval. 
    ' Generic type - Average
    '  	Formula - (N1 - N0) / (D1 - D0), where the numerator (N) represents the number 
    '		of items processed during the last sample interval and the denominator (D) 
    '		represents the number of operations completed during the last two sample 
    '		intervals. 
    '	Average (Nx - N0) / (Dx - D0)  
    '	Example PhysicalDisk\ Avg. Disk Bytes/Transfer 
    '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    Private Shared Function MyComputeCounterValue(ByVal s0 As CounterSample, ByVal s1 As CounterSample) As [Single]
        Dim numerator As [Single] = CType(s1.RawValue, [Single]) - CType(s0.RawValue, [Single])
        Dim denomenator As [Single] = CType(s1.BaseValue, [Single]) - CType(s0.BaseValue, [Single])
        Dim counterValue As [Single] = numerator / denomenator
        Return counterValue
    End Function 'MyComputeCounterValue

    ' Output information about the counter sample.
    Private Shared Sub OutputSample(ByVal s As CounterSample)
        Console.WriteLine(ControlChars.Lf + ControlChars.Cr + "+++++++++++")
        Console.WriteLine("Sample values - " + ControlChars.Lf + ControlChars.Cr)
        Console.WriteLine(("   BaseValue        = " + s.BaseValue.ToString()))
        Console.WriteLine(("   CounterFrequency = " + s.CounterFrequency.ToString()))
        Console.WriteLine(("   CounterTimeStamp = " + s.CounterTimeStamp.ToString()))
        Console.WriteLine(("   CounterType      = " + s.CounterType.ToString()))
        Console.WriteLine(("   RawValue         = " + s.RawValue.ToString()))
        Console.WriteLine(("   SystemFrequency  = " + s.SystemFrequency.ToString()))
        Console.WriteLine(("   TimeStamp        = " + s.TimeStamp.ToString()))
        Console.WriteLine(("   TimeStamp100nSec = " + s.TimeStamp100nSec.ToString()))
        Console.WriteLine("++++++++++++++++++++++")
    End Sub 'OutputSample
End Class 'App

注解

PerformanceCounter组件可用于读取现有预定义的或自定义计数器和发布 (写入) 性能数据到自定义计数器。The PerformanceCounter component can be used for both reading existing predefined or custom counters and publishing (writing) performance data to custom counters.

有许多 Windows 性能监视器中列出的预定义的计数器添加计数器对话框的There are numerous predefined counters listed in the Windows Performance Monitor's Add Counters dialog box. 若要了解有关.NET Framework 性能计数器信息,请参阅性能计数器To learn about the .NET Framework performance counters, see Performance Counters.

此类型实现IDisposable接口。This type implements the IDisposable interface. 在使用完类型后,您应直接或间接释放类型。When you have finished using the type, you should dispose of it either directly or indirectly. 若要直接释放类型,调用其Dispose中的方法try / catch块。To dispose of the type directly, call its Dispose method in a try/catch block. 若要间接释放类型,请使用 using(在 C# 中)或 Using(在 Visual Basic 中)等语言构造。To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). 有关详细信息,请参阅中的"使用对象实现 IDisposable"一节IDisposable接口主题。For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

重要

在版本 1.0 和 1.1 版.NET Framework 中,此类要求直接调用方是完全受信任。In versions 1.0 and 1.1 of the .NET Framework, this class requires immediate callers to be fully trusted. 从.NET Framework 2.0 版开始,此类要求PerformanceCounterPermission针对特定操作。Starting with the .NET Framework version 2.0, this class requires PerformanceCounterPermission for specific actions. 强烈建议PerformanceCounterPermission不授予不完全受信任的代码。It is strongly recommended that PerformanceCounterPermission not be granted to semi-trusted code. 能够读取和写入性能计数器允许代码执行操作,例如枚举执行进程并获取其相关信息。The ability to read and write performance counters allows code to perform actions such as enumerating executing processes and obtaining information about them.

此外,传递PerformanceCounter对象与不太受信任的代码可以创建一个安全问题。In addition, passing a PerformanceCounter object to less-trusted code can create a security issue. 永远不会传递性能计数器对象,如PerformanceCounterCategoryPerformanceCounter到不太受信任的代码。Never pass performance counter objects, such as a PerformanceCounterCategory or PerformanceCounter, to less trusted code.

若要读取从性能计数器,创建的实例PerformanceCounter类中,设置CategoryNameCounterName,以及 (可选)InstanceNameMachineName属性,,然后调用NextValue方法以执行性能计数器读取。To read from a performance counter, create an instance of the PerformanceCounter class, set the CategoryName, CounterName, and, optionally, the InstanceName or MachineName properties, and then call the NextValue method to take a performance counter reading.

若要发布性能计数器数据,创建一个或多个使用自定义计数器PerformanceCounterCategory.Create方法中,创建的实例PerformanceCounter类中,设置CategoryNameCounterName和 (可选)InstanceNameMachineName属性,然后调用IncrementByIncrement,或Decrement方法,或者设置RawValue属性来更改自定义计数器的值。To publish performance counter data, create one or more custom counters using the PerformanceCounterCategory.Create method, create an instance of the PerformanceCounter class, set the CategoryName, CounterName and, optionally, InstanceName or MachineName properties, and then call the IncrementBy, Increment, or Decrement methods, or set the RawValue property to change the value of your custom counter.

备注

IncrementIncrementBy,和Decrement方法使用联锁更新计数器值。The Increment, IncrementBy, and Decrement methods use interlocks to update the counter value. 这可以帮助使计数器值准确在多线程或多进程的情况下,但也会产生对性能产生负面影响。This helps keep the counter value accurate in multithreaded or multiprocess scenarios, but also results in a performance penalty. 如果不需要的准确性,互锁操作提供,可以更新RawValue属性直接为最多 5 倍的性能提高。If you do not need the accuracy that interlocked operations provide, you can update the RawValue property directly for up to a 5 times performance improvement. 但是,在多线程方案中,为计数器值的某些更新可能被忽略,从而导致不准确的数据。However, in multithreaded scenarios, some updates to the counter value might be ignored, resulting in inaccurate data.

该计数器是按性能收集数据的机制。The counter is the mechanism by which performance data is collected. 注册表存储的所有计数器,其中每个相关系统功能的特定区域的名称。The registry stores the names of all the counters, each of which is related to a specific area of system functionality. 示例包括处理器的忙时间、 内存使用情况或通过网络连接接收的字节数。Examples include a processor's busy time, memory usage, or the number of bytes received over a network connection.

通过其名称和其位置唯一标识每个计数器。Each counter is uniquely identified through its name and its location. 在文件路径包括驱动器、 目录、 一个或多个子目录和文件名称相同的方式,计数器的信息包含以下四个元素: 计算机、 类别、 类别实例和计数器名称。In the same way that a file path includes a drive, a directory, one or more subdirectories, and a file name, counter information consists of four elements: the computer, the category, the category instance, and the counter name.

类别或性能对象,该计数器测量的数据,必须包括的计数器信息。The counter information must include the category, or performance object, that the counter measures data for. 计算机的类别包括物理组件,如处理器、 磁盘和内存。A computer's categories include physical components, such as processors, disks, and memory. 也有系统类别,如进程和线程。There are also system categories, such as processes and threads. 分配有一组标准计数器和每个类别相关的功能元素在计算机中。Each category is related to a functional element within the computer and has a set of standard counters assigned to it. 在 Windows 2000 系统监视器中,添加计数器对话框的性能对象下拉列表中列出了这些对象,你必须将其包含的计数器路径中。These objects are listed in the Performance object drop-down list of the Add Counters dialog box within the Windows 2000 System Monitor, and you must include them in the counter path. 性能数据是按分组到类别它相关。Performance data is grouped by the category to which is it related.

在某些情况下,可以存在同一类别的多个副本。In certain cases, several copies of the same category can exist. 例如,多个进程和线程同时运行,并且有些计算机包含多个处理器。For example, several processes and threads run simultaneously, and some computers contain more than one processor. 类别副本称为类别实例,并且每个实例都有一组分配给它的标准计数器。The category copies are called category instances, and each instance has a set of standard counters assigned to it. 如果类别可以有多个实例,实例规范必须包含的计数器信息中。If a category can have more than one instance, an instance specification must be included in the counter information.

若要获取执行必要的计算所需的初始或上一个值的计数器的性能数据,请调用NextValue方法两次,并使用返回的信息,根据你的应用程序的需要。To obtain performance data for counters that required an initial or previous value for performing the necessary calculation, call the NextValue method twice and use the information returned as your application requires.

备注

与安装的性能计数器类别.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. 可以通过创建 DWORD 注册表项 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services 中名为 FileMappingSize 指定单独的共享内存的大小\<类别名称 > \性能。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>.

构造函数

PerformanceCounter() PerformanceCounter() PerformanceCounter() PerformanceCounter()

初始化 PerformanceCounter 类的新的只读实例,但不将该实例与任何系统性能计数器或自定义性能计数器关联。Initializes a new, read-only instance of the PerformanceCounter class, without associating the instance with any system or custom performance counter.

PerformanceCounter(String, String) PerformanceCounter(String, String) PerformanceCounter(String, String) PerformanceCounter(String, String)

初始化 PerformanceCounter 类的新的只读实例,并将其与本地计算机上指定的系统性能计数器或自定义性能计数器关联。Initializes a new, read-only instance of the PerformanceCounter class and associates it with the specified system or custom performance counter on the local computer. 此构造函数要求该类别包含单个实例。This constructor requires that the category have a single instance.

PerformanceCounter(String, String, Boolean) PerformanceCounter(String, String, Boolean) PerformanceCounter(String, String, Boolean) PerformanceCounter(String, String, Boolean)

初始化 PerformanceCounter 类的新的只读或读/写实例,并将其与本地计算机上指定的系统性能计数器或自定义性能计数器关联。Initializes a new, read-only or read/write instance of the PerformanceCounter class and associates it with the specified system or custom performance counter on the local computer. 此构造函数要求该类别包含单个实例。This constructor requires that the category contain a single instance.

PerformanceCounter(String, String, String) PerformanceCounter(String, String, String) PerformanceCounter(String, String, String) PerformanceCounter(String, String, String)

初始化 PerformanceCounter 类的新的只读实例,并将其与本地计算机上指定的系统性能计数器或自定义性能计数器及类别实例关联。Initializes a new, read-only instance of the PerformanceCounter class and associates it with the specified system or custom performance counter and category instance on the local computer.

PerformanceCounter(String, String, String, Boolean) PerformanceCounter(String, String, String, Boolean) PerformanceCounter(String, String, String, Boolean) PerformanceCounter(String, String, String, Boolean)

初始化 PerformanceCounter 类的新的只读实例或读/写实例,并将其与本地计算机上指定的系统性能计数器或自定义性能计数器及类别实例关联。Initializes a new, read-only or read/write instance of the PerformanceCounter class and associates it with the specified system or custom performance counter and category instance on the local computer.

PerformanceCounter(String, String, String, String) PerformanceCounter(String, String, String, String) PerformanceCounter(String, String, String, String) PerformanceCounter(String, String, String, String)

初始化 PerformanceCounter 类的新的只读实例,并将其与指定计算机上指定的系统性能计数器或自定义性能计数器及类别实例关联。Initializes a new, read-only instance of the PerformanceCounter class and associates it with the specified system or custom performance counter and category instance, on the specified computer.

字段

DefaultFileMappingSize DefaultFileMappingSize DefaultFileMappingSize DefaultFileMappingSize

指定由性能计数器共享的全局内存的大小(以字节为单位)。Specifies the size, in bytes, of the global memory shared by performance counters. 默认大小为 524,288 个字节。The default size is 524,288 bytes.

属性

CanRaiseEvents CanRaiseEvents CanRaiseEvents CanRaiseEvents

获取一个指示组件是否可以引发事件的值。Gets a value indicating whether the component can raise an event.

(Inherited from Component)
CategoryName CategoryName CategoryName CategoryName

获取或设置此性能计数器的性能计数器类别的名称。Gets or sets the name of the performance counter category for this performance counter.

Container Container Container Container

获取 IContainer,它包含 ComponentGets the IContainer that contains the Component.

(Inherited from Component)
CounterHelp CounterHelp CounterHelp CounterHelp

获取此性能计数器的说明。Gets the description for this performance counter.

CounterName CounterName CounterName CounterName

获取或设置与此 PerformanceCounter 实例关联的性能计数器的名称。Gets or sets the name of the performance counter that is associated with this PerformanceCounter instance.

CounterType CounterType CounterType CounterType

获取关联的性能计数器的计数器类型。Gets the counter type of the associated performance counter.

DesignMode DesignMode DesignMode DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
Events Events Events Events

获取附加到此 Component 的事件处理程序的列表。Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
InstanceLifetime InstanceLifetime InstanceLifetime InstanceLifetime

获取或设置进程的生存期。Gets or sets the lifetime of a process.

InstanceName InstanceName InstanceName InstanceName

获取或设置此性能计数器的实例名称。Gets or sets an instance name for this performance counter.

MachineName MachineName MachineName MachineName

获取或设置此性能计数器的计算机名。Gets or sets the computer name for this performance counter

RawValue RawValue RawValue RawValue

获取或设置此计数器的原始值(即未经过计算的值)。Gets or sets the raw, or uncalculated, value of this counter.

ReadOnly ReadOnly ReadOnly ReadOnly

获取或设置一个值,该值指示此 PerformanceCounter 实例是否处于只读模式。Gets or sets a value indicating whether this PerformanceCounter instance is in read-only mode.

Site Site Site Site

获取或设置 ComponentISiteGets or sets the ISite of the Component.

(Inherited from Component)

方法

BeginInit() BeginInit() BeginInit() BeginInit()

开始初始化在窗体上使用或由另一个组件使用的 PerformanceCounter 实例。Begins the initialization of a PerformanceCounter instance used on a form or by another component. 此初始化在运行时发生。The initialization occurs at runtime.

Close() Close() Close() Close()

关闭性能计数器并释放由此性能计数器实例分配的所有资源。Closes the performance counter and frees all the resources allocated by this performance counter instance.

CloseSharedResources() CloseSharedResources() CloseSharedResources() CloseSharedResources()

释放由计数器分配的性能计数器库共享状态。Frees the performance counter library shared state allocated by the counters.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Decrement() Decrement() Decrement() Decrement()

通过有效的原子操作使关联的性能计数器减一。Decrements the associated performance counter by one through an efficient atomic operation.

Dispose() Dispose() Dispose() Dispose()

释放由 Component 使用的所有资源。Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

释放由 Component 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Inherited from Component)
EndInit() EndInit() EndInit() EndInit()

结束在窗体上使用或由另一组件使用的 PerformanceCounter 实例的初始化。Ends the initialization of a PerformanceCounter instance that is used on a form or by another component. 此初始化在运行时发生。The initialization occurs at runtime.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetService(Type) GetService(Type) GetService(Type) GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
Increment() Increment() Increment() Increment()

通过有效的原子操作使关联的性能计数器增加一。Increments the associated performance counter by one through an efficient atomic operation.

IncrementBy(Int64) IncrementBy(Int64) IncrementBy(Int64) IncrementBy(Int64)

通过有效的原子操作,使关联的性能计数器的值增加或减少指定的量。Increments or decrements the value of the associated performance counter by a specified amount through an efficient atomic operation.

InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
NextSample() NextSample() NextSample() NextSample()

获取计数器样本,并为其返回原始值(即未经过计算的值)。Obtains a counter sample, and returns the raw, or uncalculated, value for it.

NextValue() NextValue() NextValue() NextValue()

获取计数器样本并为其返回计算所得值。Obtains a counter sample and returns the calculated value for it.

RemoveInstance() RemoveInstance() RemoveInstance() RemoveInstance()

删除由 PerformanceCounter 对象的 InstanceName 属性指定的类别实例。Deletes the category instance specified by the PerformanceCounter object InstanceName property.

ToString() ToString() ToString() ToString()

返回包含 Component 的名称的 String(如果有)。Returns a String containing the name of the Component, if any. 不应重写此方法。This method should not be overridden.

(Inherited from Component)

事件

Disposed Disposed Disposed Disposed

当通过调用 Dispose() 方法释放组件时发生。Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)

适用于

另请参阅