HOW TO:新增及移除效能計數器執行個體
更新:2007 年 11 月
當您使用計數器和分類時,可以動態加入和移除執行個體。例如,您可以為 Web 架構零售應用程式的每位使用者加入執行個體,這樣一來,您就可以追蹤他們的動作資訊,並在使用者工作階段結束時移除執行個體。
您可以為計數器設定原始值來加入執行個體。如果計數器還沒有執行個體存在,當您第一次設定 RawValue 屬性時將建立執行個體,而且若未指定其他執行個體,則假設對未經處理值的所有後續動作都會影響該執行個體。您可以藉由指定新的執行個體名稱並在之後設定值,即可建立其他的執行個體。
![]() |
---|
會建立執行個體的過程是設定執行個體的值,而非指定新執行個體的名稱。 |
和計數器不同的是,執行個體可以隨時加入至使用者定義分類或自其中移除,而計數器無法加入至現有分類,除非在分類建立時加入。您可以使用 InstanceName 屬性從某個執行個體切換控制至其他執行個體。
您可以使用 RemoveInstance 方法,從記憶體中移除自訂效能計數器的執行個體。例如,假設您有個使用 OrderInProgress 分類的 Web 架構零售應用程式,您會在其中為每位使用者目前的購物車維護執行個體。當使用者第一次加入項目至購物車時,您的應用程式會為該使用者建立新的執行個體。當使用者完成訂購時,您的應用程式會刪除該執行個體。在訂購過程中,您會更新含有諸如 NumberofItemsinCart、TimeSinceCreation 和 NumberofItemsAddedPerSecond 等計數器的執行個體。
您無法從屬於 Windows 預設部分的效能計數器移除執行個體。如果您的 PerformanceCounter 元件沒有參考有效的執行個體,此方法將擲回例外狀況。
![]() |
---|
Microsoft Windows NT 4.0 版並未完全支援 PerformanceCounter 類別。您可讀取系統計數器,但是您無法建立、寫入或刪除自訂計數器。 |
若要加入效能計數器執行個體
正常地建立分類和計數器。如需詳細資訊,請參閱 HOW TO:建立效能計數器分類。
將 InstanceName 屬性設定為執行個體的唯一名稱,再設定執行個體的 RawValue 屬性。
下列程式碼顯示如何建立現有效能計數器分類的幾個執行個體:
' Assumes the category and counter have already been created. Dim myCounter As New System.Diagnostics.PerformanceCounter( _ "cat", "counter", "instance1", False) ' Set the raw value to automatically create instance1. myCounter.RawValue = 100 ' State that you will now be working with a different instance. myCounter.InstanceName = "instance2" ' Setting the value actually creates instance2. myCounter.RawValue = 200
// Assumes category and counter have been created. System.Diagnostics.PerformanceCounter myCounter = new System.Diagnostics.PerformanceCounter( "cat", "counter", "instance1", false); // Set the raw value to automatically create instance1. myCounter.RawValue = 100; // State that you will now be working with a different instance. myCounter.InstanceName = "instance2"; // Setting the value actually creates instance2. myCounter.RawValue = 200;
若要移除效能計數器執行個體
建立連接到您想移除執行個體之計數器的 PerformanceCounter 元件執行個體。如需詳細資訊,請參閱 HOW TO:建立 PerformanceCounter 元件執行個體。
將 InstanceName 屬性設定為您想刪除的執行個體。
呼叫元件的 RemoveInstance 方法。
下列範例顯示如何從計數器中移除稱為 Reference 的執行個體:
' Assumes that you have configured PerformanceCounter1 to ' interact with the appropriate counter. PerformanceCounter1.InstanceName = "Reference" PerformanceCounter1.RemoveInstance()
// Assumes that you have configured PerformanceCounter1 to // interact with the appropriate counter. PerformanceCounter1.InstanceName = "Reference"; PerformanceCounter1.RemoveInstance();
請參閱
工作
HOW TO:建立 PerformanceCounter 元件執行個體