列出类别的所有性能计数器

时间:2009-08-20 09:10:17

标签: c# performance performancecounter

System.Diagnostics中是否有内置方法用于检索给定CategoryName的所有实例化性能计数器?

我们有许多使用自定义性能计数器的多线程应用程序,现在需要添加一个仪表板来显示性能统计信息。

我想以这样的方式制作仪表板,只要有人在新代码中添加新计数器,就不需要更新它。

2 个答案:

答案 0 :(得分:25)

试试这个:

public void ListCounters(string categoryName)
{
    PerformanceCounterCategory category = PerformanceCounterCategory.GetCategories().First(c => c.CategoryName == categoryName);
    Console.WriteLine("{0} [{1}]", category.CategoryName, category.CategoryType);

    string[] instanceNames = category.GetInstanceNames();

    if (instanceNames.Length > 0)
    {
        // MultiInstance categories
        foreach (string instanceName in instanceNames)
        {
            ListInstances(category, instanceName);
        }
    }
    else
    {
        // SingleInstance categories
        ListInstances(category, string.Empty);
    }
}

private static void ListInstances(PerformanceCounterCategory category, string instanceName)
{
    Console.WriteLine("    {0}", instanceName);
    PerformanceCounter[] counters = category.GetCounters(instanceName);

    foreach (PerformanceCounter counter in counters)
    {
        Console.WriteLine("        {0}", counter.CounterName);
    }
}

您必须了解可以拥有多个实例的类别,并以稍微不同的方式处理这些类别。

答案 1 :(得分:6)

只是为了好玩..在linq的1行中这是同样的事情:

PerformanceCounterCategory
.GetCategories()
.Where(cat => cat.CategoryName == "ASP.NET v4.0.30319")
.Select (cat => cat.GetInstanceNames().Any() ? cat.GetInstanceNames().Select (i => cat.GetCounters(i)).SelectMany (counter => counter) : cat.GetCounters("")).SelectMany (counter => counter)
.Select(counter => string.Format("{0} : {1}.{2}", counter.InstanceName , counter.CategoryName, counter.CounterName))