列出类别中的所有性能计数器(List all performance counters for a

2019-07-02 12:33发布

是否有System.Diagnostics程序检索所有实例的性能计数器对于给定的类别名称内置的方法?

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

我想使仪表板,使得它并不需要更新,每当有人添加了一个新的计数器到一个新的代码的方式。

Answer 1:

试试这个:

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);
    }
}

你必须要知道,可以有多个实例,并与处理略有不同类别。



Answer 2:

只是为了好玩..这里是在1线LINQ同样的事情:

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))


文章来源: List all performance counters for a category