共用方式為


PerformanceCounter 類別

定義

代表 Windows NT 效能計數器元件。

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
實作

範例

以下程式碼範例示範如何使用該 PerformanceCounter 類別來建立並使用 AverageCount64 計數器型別。 範例中建立類別、設置計數器、從計數器收集資料,並呼叫 CounterSampleCalculator 類別來解讀效能計數器資料。 中間和最終成績會顯示在主控台視窗中。 關於其他效能計數器類型的更多範例,請參閱列 PerformanceCounterType 舉。

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 元件可用於讀取現有的預定義或自訂計數器,並能將效能資料發佈(寫入)至自訂計數器。

Windows 效能監控器的 「新增計數器」對話框中列出了許多預設的計數器。 想了解 .NET Framework 的效能計數器,請參見 效能計數器

此類型會實作 IDisposable 介面。 當您完成使用這個物品後,應直接或間接地處理它。 若要直接處置類型,請在 Disposetry/ 區塊中呼叫其 catch 方法。 若要間接處置它,請使用語言建構,例如 using (C#) 或 Using (在 Visual Basic 中)。 如需詳細資訊,請參閱介面主題中的 <使用實作 IDisposable 的物件>一節。

這很重要

在 .NET Framework 1.0 與 1.1 版本中,此類別要求立即呼叫者必須完全信任。 從 .NET Framework 2.0 版本開始,這個類別需要 PerformanceCounterPermission 執行特定的動作。 強烈建議 PerformanceCounterPermission 不要授予半信任的程式碼。 讀取與寫入效能計數器的能力使程式碼能執行如列舉執行中的程序及獲取相關資訊等動作。

此外,將物件傳 PerformanceCounter 給較不信任的程式碼也可能引發安全問題。 切勿將效能計數器物件(如 a PerformanceCounterCategoryPerformanceCounter)傳給較不信任的程式碼。

要從效能計數器讀取,先建立該類別的實例 PerformanceCounter ,設定 CategoryNameCounterName,以及(可選地) InstanceName 的 OR MachineName 屬性,然後呼叫 NextValue 該方法來讀取效能計數器。

要發佈效能計數器資料,請使用該 PerformanceCounterCategory.Create 方法建立一個或多個自訂計數器,建立類別實例 PerformanceCounter ,設定 CategoryName、 或 CounterName ,可選性 InstanceNameMachineName 地,然後呼叫 IncrementByIncrementDecrement 方法,或設定 RawValue 屬性以改變自訂計數器的值。

備註

這些、 IncrementIncrementByDecrement 方法會使用互鎖來更新計數器值。 這有助於在多執行緒或多程序情境下保持計數器的準確度,但同時也會帶來效能損失。 如果你不需要互鎖操作所提供的精確度,你可以直接更新 RawValue 屬性,效能提升最多可達 5 倍。 然而,在多執行緒情境下,計數器值的部分更新可能會被忽略,導致資料不準確。

計數器是收集效能數據的機制。 登錄檔儲存所有計數器的名稱,每個計數器名稱都與系統功能的特定區域相關聯。 例如處理器的忙碌時間、記憶體使用量,或透過網路連線接收的位元組數。

每個計數器都以其名稱和位置唯一識別。 就像檔案路徑包含磁碟機、目錄、一個或多個子目錄以及一個檔名一樣,計數器資訊由四個元素組成:電腦、類別、類別實例和計數器名稱。

計數器資訊必須包含計數器所用資料的類別或效能物件。 電腦的類別包括實體元件,如處理器、磁碟和記憶體。 還有系統類別,如程序與執行緒。 每個類別都與電腦中的一個功能元素相關聯,並指派一組標準計數器。 這些物件會列在 Windows 2000 系統監控器中「新增計數器」對話框的效能物件下拉選單中,且必須將它們包含在計數器路徑中。 績效數據依其相關類別分組。

在某些情況下,同一類別的多個副本可能會存在。 例如,多個程序和執行緒同時執行,有些電腦包含多個處理器。 這些類別副本稱為類別實例,每個實例都有一組標準計數器。 若一個類別可以有多個實例,計數器資訊中必須包含實例規格。

若要取得需要初始值或先前數值才能執行必要計算的計數器的效能資料,請呼叫 NextValue 該方法兩次,並依應用程式需求使用回傳的資訊。

備註

安裝於 .NET 的效能計數器類別使用獨立的共享記憶體,每個效能計數器類別都有自己的記憶體。 你可以在登錄檔鍵 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<類別名稱>\效能中建立名為 FileMappingSize 的 DWORD 來指定獨立共享記憶體的大小。 FileMappingSize 值設為該類別的共享記憶體大小。 預設大小為131072小數。 若 FileMappingSize 值不存在,則 fileMappingSize 會使用 Machine.config 檔案中指定的屬性值 performanceCounters ,這會增加組態檔案處理的額外負擔。 你可以透過在登錄檔設定檔案映射大小來實現應用程式啟動效能的提升。 欲了解更多檔案映射大小的資訊,請參閱 <performanceCounters>

建構函式

名稱 Description
PerformanceCounter()

初始化該類別的新唯讀實例 PerformanceCounter ,且不將該實例與任何系統或自訂效能計數器關聯。

PerformanceCounter(String, String, Boolean)

初始化該類別的新、唯讀或讀寫實例 PerformanceCounter ,並將其與本地電腦上的指定系統或自訂效能計數器關聯。 此建構子要求類別包含單一實例。

PerformanceCounter(String, String, String, Boolean)

初始化該類別的新、唯讀或讀寫實例 PerformanceCounter ,並將其關聯到本地電腦上的指定系統或自訂效能計數器及類別實例。

PerformanceCounter(String, String, String, String)

初始化該類別的新唯讀實例 PerformanceCounter ,並將其與指定系統或自訂效能計數器及類別實例關聯,並設置於指定電腦上。

PerformanceCounter(String, String, String)

初始化該類別的新唯讀實例 PerformanceCounter ,並將其與本地電腦上的指定系統或自訂效能計數器及類別實例關聯。

PerformanceCounter(String, String)

初始化該類別的新唯讀實例 PerformanceCounter ,並將其與本地電腦上的指定系統或自訂效能計數器關聯。 此構造子要求類別必須有單一實例。

欄位

名稱 Description
DefaultFileMappingSize
已淘汰.
已淘汰.
已淘汰.

指定效能計數器共享的全域記憶體大小(以位元組為單位)。 預設大小為 524,288 位元組。

屬性

名稱 Description
CanRaiseEvents

會得到一個值,表示該元件是否能引發事件。

(繼承來源 Component)
CategoryName

取得或設定該效能計數器類別的名稱。

Container

得到 IContainer 包含 Component的 。

(繼承來源 Component)
CounterHelp

會看到這個效能計數器的描述。

CounterName

取得或設定與此 PerformanceCounter 實例相關的效能計數器名稱。

CounterType

取得相關效能計數器的計數器類型。

DesignMode

會得到一個值,表示目前 Component 是否處於設計模式。

(繼承來源 Component)
Events

會取得與此 Component連結的事件處理程序清單。

(繼承來源 Component)
InstanceLifetime

取得或設定一個程序的壽命。

InstanceName

取得或設定這個效能計數器的實例名稱。

MachineName

取得或設定這個效能計數器的電腦名稱。

RawValue

取得或設定此計數器的原始值(未計算值)。

ReadOnly

取得或設定一個值,表示此 PerformanceCounter 實例是否處於唯讀模式。

Site

取得或設定 ISiteComponent

(繼承來源 Component)

方法

名稱 Description
BeginInit()

開始初始 PerformanceCounter 化用於表單或其他元件的實例。 初始化發生在執行時。

Close()

關閉效能計數器,釋放由此效能計數器實例分配的所有資源。

CloseSharedResources()

釋放由計數器分配的效能計數器庫共享狀態。

CreateObjRef(Type)

建立一個物件,包含產生代理伺服器所需的所有相關資訊,用於與遠端物件通訊。

(繼承來源 MarshalByRefObject)
Decrement()

透過高效的原子運算,將相關的效能計數器降低一倍。

Dispose()

釋放所有由 Component.

(繼承來源 Component)
Dispose(Boolean)

釋放 未管理的資源, Component 並可選擇性地釋放受管理資源。

(繼承來源 Component)
EndInit()

終止用於表單或其他元件的實例初始化 PerformanceCounter 。 初始化發生在執行時。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetHashCode()

做為預設哈希函式。

(繼承來源 Object)
GetLifetimeService()
已淘汰.

取得目前控制此實例生命週期政策的終身服務物件。

(繼承來源 MarshalByRefObject)
GetService(Type)

回傳一個由 或Component其 所提供的Container服務的物件。

(繼承來源 Component)
GetType()

取得目前實例的 Type

(繼承來源 Object)
Increment()

透過高效的原子運算,將相關的效能計數器增加一。

IncrementBy(Int64)

透過高效的原子操作,將相關效能計數器的值增加或減少指定幅度。

InitializeLifetimeService()
已淘汰.

取得一個終身服務物件以控制此實例的終身政策。

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object的淺層複本。

(繼承來源 Object)
MemberwiseClone(Boolean)

建立一個 MarshalByRefObject 目前物件的淺層複製品。

(繼承來源 MarshalByRefObject)
NextSample()

取得計數器取樣,並回傳其原始值(未計算值)。

NextValue()

取得一個計數取樣,並回傳計算出來的值。

RemoveInstance()

刪除物件PerformanceCounterInstanceName屬性指定的類別實例。

ToString()

回傳 String 包含 的名稱 Component(若有的話)。 此方法不應被覆蓋。

(繼承來源 Component)

事件

名稱 Description
Disposed

當元件被呼叫方法 Dispose() 時會發生。

(繼承來源 Component)

適用於

另請參閱