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

标签 .net system.diagnostics

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

因此,我围绕 PerformanceCounter 创建了包装器,并在第一次使用时检查 PerfCounter 是否存在。如果它们存在,那么我将使用 native PerformanceCounter,而不是使用不执行任何操作的包装器。

因此,为了检查性能计数器是否存在,我使用 PerformanceCounterCategory.Exists

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

我能做什么?

自行尝试的代码: 使用系统; 使用系统诊断;

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

最佳答案

这似乎是无法避免的事情。来自 MSDN:

Use of the Exists method can result in a noticeable performance penalty while all performance counters on the machine are checked for availability. If you are only writing to a performance counter, you can avoid the global search for performance counters by creating the performance counter when the application is installed and assuming the category exists when accessing the counter. There is no way to avoid the performance counter search when reading from performance counters.

重点是我的。

关于.net - 如果类别不存在,PerformanceCounterCategory.Exists 会非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2655067/

相关文章:

c# - 在接收到新行之前读取 Process StandardOutput

c# - 在字典中序列化 HashSet

.net - 我可以返回特定泛型类型的所有泛型对象吗?

c# - 执行 System.Diagnostics.Process cmd.exe 仅打开命令提示符,不执行参数

c# - 如何运行一个不知道参数从哪里开始的程序?

c# - 在Windows 7下启动System.Diagnostics.Process时出现问题

.net - F# Guideline 是否建议声明具有相同名称的模块和类型?

c# - 如何防止 .NET 运行时中的静态变量共享?

c# - 以最少的内存消耗将文本文件解析为列表

c# - System.Diaganostics.Process.Id 与任务管理器中显示的进程 ID 不同。为什么?