PerformanceCounterCategory.Exists is very slow if the category does not exist

I have a library that uses a bunch of its own counters. But I want my library to work fine, even if these counters were not installed.

So, I created wrappers aroung PerformanceCounter and on first use it checks if PerfCounter exists or not. If they exist, then I use my own PerformanceCounter, instead I use a shell that does nothing.

So, to check the existence of a punch, I use PerformanceCounterCategory.Exists

The problem is that if there is no such category, then PerformanceCounterCategory.Exists makes a call (on my machine) for about 10 seconds! Needless to say this too slowly.

What can I do?

Code to try it yourself: using the system; using 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);
}
}
+3
source share
1 answer

This cannot be avoided. From MSDN:

Using the Exists method can result in a noticeable penalty for execution while all performance counters on the machine are checked for availability. If you write only a performance counter, you can avoid the global search for performance counters by creating a performance counter when the application is installed and if the category exists when access to the counter. There is no way to avoid performance counter searches when reading from the results counters.

The emphasis is mine.

+6
source

Source: https://habr.com/ru/post/1741489/


All Articles