根据您的描述,我相信您想要创建自定义计数器。您可以一次创建计数器,但您必须一个一个地创建它们的实例。
使用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
}