8

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

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

我想以这样一种方式制作仪表板,即每当有人将新计数器添加到新代码中时,它都不需要更新。

4

2 回答 2

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

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

于 2009-08-20T10:05:49.540 回答
6

只是为了好玩..这是 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))
于 2013-02-18T18:32:20.140 回答