按照你的描述我相信你想創建自定義計數器。您可以一次創建計數器,但您必須逐個創建實例。使用CounterCreationDataCollection和CounterCreationData類。首先,創建計數器數據,將它們添加到新的計數器類別,然後創建自己的實例:
//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
}
不知道爲什麼有人downvoted這個問題... – jsmith 2012-07-24 15:33:00