2

有没有办法获得性能计数器的集合?

我的意思是,而不是创建几个性能计数器,例如

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

我想获得一个集合(用于 CategoryName),其中每个项目都是 CounterName 项目。

所以不需要单独的计数器创建。

4

1 回答 1

3

根据您的描述,我相信您想要创建自定义计数器。您可以一次创建计数器,但您必须一个一个地创建它们的实例。

使用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
}
于 2012-07-24T15:08:59.760 回答