按照你的描述我相信你想创建自定义计数器。您可以一次创建计数器,但您必须逐个创建实例。使用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