如果类别不存在,PerformanceCounterCategory.Exists非常慢

Shr*_*ike 3 .net system.diagnostics

我有一种库,它使用一堆自己的perf计数器.但我希望我的库工作正常,即使没有安装perf计数器.

所以我已经在PerformanceCounter上创建了包装器,并在第一次使用时检查PerfCounter是否存在.如果它们存在,那么我使用本机PerformanceCounter而不是我使用的包装器什么都不做.

因此,为了检查perf计数器的存在,我使用了PerformanceCounterCategory.Exists

问题是,如果没有这样的类别,那么PerformanceCounterCategory.Exists调用(在我的机器上)大约需要10秒!不用说它太慢了.

我能做什么?

代码自己尝试:使用System; 使用System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        var ts = Stopwatch.StartNew();
        var res = PerformanceCounterCategory.Exists("XYZ");
        Console.WriteLine(ts.ElapsedMilliseconds);
        Console.WriteLine("result:" + res);
}
}
Run Code Online (Sandbox Code Playgroud)

Joã*_*elo 6

这似乎是无法避免的.来自MSDN:

使用Exists方法会导致显着的性能损失,同时检查计算机上的所有性能计数器的可用性. 如果您只是写入性能计数器,则可以通过在安装应用程序时创建性能计数器并假设访问计数器时存在类别来避免全局搜索性能计数器.从性能计数器读取时,无法避免性能计数器搜索.

重点是我的.