Search code examples
.netperformancecounter

Writable Performance Counter doesn't throw exception


Using .NET 4.7, reference source here. According to the docs, the constructor public PerformanceCounter (string categoryName, string counterName, string instanceName, bool readOnly); should throw an InvalidOperationException if the counterName doesn't exist.

But as you can see from the source, it only does this check if the counter is read-only. For example, this returns just fine:

new PerformanceCounter("ExistingCategory","NameDefinitelyDoesntExist", "ExistingInstance, false)`

So, will I run into a runtime exception later on? I am otherwise assuming that as long as the counter is writable and the category name exists, the corresponding performance counter doesn't need to actually exist on the local machine.

I want to do this just so I can write some code using the performance counter that will run on a lot of machines without going through the drudgery of making sure the counter exists on every machine.


Solution

  • Well, methinks you can always read from a writable PerformanceCounter, so the difference in behavior is odd. The docs are certainly incorrect here.

    It looks .NET is trying to antipicate your whim, as an InvalidOperationException will be thrown when NextValue(), the method for reading from a performance counter, is called, whether or not it is read-only. For a read-only performance counter, this is one of the only methods you would wish to invoke, and .NET will simply throw the exception sooner rather than later.

    Furthermore it appears that writing to the performance counter (via RawValue, IncrementBy, Decrement, etc.) will succeed whether or not the corresponding Windows counter actually exists, as our celebrity guest Hans Passant has suggested.