2012-07-24 103 views
1

有什麼辦法可以獲得性能計數器的集合嗎?性能計數器集合

我的意思是,而不是創建幾個性能計數器,如

PerformanceCounter actions = new PerformanceCounter("CategoryName", "CounterName1","instance"); 
PerformanceCounter tests = new PerformanceCounter("CategoryName", "CounterName2", "instance"); 

我想獲得一個集合(類別名稱),其中每個項目將是一個CounterName項目。

所以沒有必要在單獨的櫃檯創作。

+2

不知道爲什麼有人downvoted這個問題... – jsmith 2012-07-24 15:33:00

回答

2

按照你的描述我相信你想創建自定義計數器。您可以一次創建計數器,但您必須逐個創建實例。使用CounterCreationDataCollectionCounterCreationData類。首先,創建計數器數據,將它們添加到新的計數器類別,然後創建自己的實例:

//Create the counters data. You could also use a loop here if your counters will have exactly these names. 
CounterCreationDataCollection counters = new CounterCreationDataCollection(); 
counters.Add(new CounterCreationData("CounterName1", "Description of Counter1", PerformanceCounterType.AverageCount64)); 
counters.Add(new CounterCreationData("CounterName2", "Description of Counter2", PerformanceCounterType.AverageCount64)); 

//Create the category with the prwviously defined counters. 
PerformanceCounterCategory.Create("CategoryName", "CategoryDescription", PerformanceCounterCategoryType.MultiInstance, counters); 

//Create the Instances 
CategoryName actions = new PerformanceCounter("CategoryName", "CounterName1", "Instance1", false)); 
CategoryName tests = new PerformanceCounter("CategoryName", "CounterName2", "Instance1", false)); 

我的建議是不要使用通用名稱作爲計數器名稱。創建計數器之後,您可能想要收集其數據(可能是通過性能監視器),因此而不是使用CounteName1作爲計數器表示的名稱(例如,動作,測試...)。

編輯

爲了得到一個特定類別的所有計數器一次創建計數器類的一個實例,並使用GetCounters方法:

PerformanceCounterCategory category = new PerformanceCounterCategory("CategoryName"); 
PerformanceCounter[] counters = category.GetCounters("instance"); 

foreach (PerformanceCounter counter in counters) 
{ 
    //do something with the counter 
} 
+0

實際上不是, 我不想創建自定義計數器,但我想使用內置計數器的應用程序。 因此,我不希望將每個性能計數器作爲獨立單元來創建,而是希望一次獲得某個類別名稱的所有數據(計數器)......是否有可能? 謝謝 – Igal 2012-07-25 11:07:52

+1

@ user301639請檢查我編輯的答案。我希望這是你想要的。 – Schaliasos 2012-07-25 11:35:14

+1

太棒了,這是我尋找的方式。 謝謝 – Igal 2012-08-01 12:08:10