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

    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

    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

    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

    '++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++
    '	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
End Class

備註

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. 若要直接處置型別,請呼叫其 try/catch 區塊中的 Dispose 方法。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.

重要

在 .NET Framework 的版本1.0 和1.1 中,此類別需要立即呼叫端完全受信任。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類別的實例、 CategoryName設定、 CounterName和(選擇性) 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屬性。然後,呼叫IncrementByIncrementDecrement方法,或設定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.

注意

Increment、和方法Decrement會使用 interlocks 來更新計數器值。 IncrementByThe 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. 您可以在登錄機碼 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ <類別目錄名稱中建立名為 FileMappingSize 的 DWORD,以指定個別共用記憶體的大小 > \Performance。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 decimal。The default size is 131072 decimal. 如果 FileMappingSize 值不存在, fileMappingSize則會使用 machine.config 檔案中指定之performanceCounters元素的屬性值,導致設定檔案處理的額外負荷。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. 這個建構函式 (Constructor) 要求分類包含單一執行個體。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

取得包含 IContainerComponentGets 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

取得或設定處理序的存留期 (Lifetime)。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)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。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()

經由有效率的不可部分完成的作業 (Atomic Operation),將相關的效能計數器逐一遞減。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 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。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()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。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 的淺層複本 (Shallow Copy)。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 名稱的 StringReturns 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)

適用於

另請參閱