I've been banging my head against the wall all day trying to solve this issue...
Let's say I execute the following block of code inside a console application that starts up and runs this block of code within seconds of launching:
var p = new PerformanceCounter(".NET CLR Jit", "# of Methods Jitted","Process Name", true);
long raw = p.RawValue; //throws
I get the following exception:
System.InvalidOperationException: The Counter layout for the Category specified is invalid, a counter of the type: AverageCount64, AverageTimer32, CounterMultiTimer, CounterMultiTimerInverse, CounterMultiTimer100Ns, CounterMultiTimer100NsInverse, RawFraction, or SampleFraction has to be immediately followed by any of the base counter types: AverageBase, CounterMultiBase, RawBase or SampleBase.
[01:23:02][Step 1/1] at System.Diagnostics.CategorySample.GetCounterDefinitionSample(String counter)
[01:23:02][Step 1/1] at System.Diagnostics.PerformanceCounter.NextSample()
[01:23:02][Step 1/1] at System.Diagnostics.PerformanceCounter.NextValue()
These are built-in CLR counters, and I've verified that they are correctly installed on the target machine.
Here's what is really weird: if I have Performance Monitor out and I refresh my list of available counter instances as the process launches, everything works fine and every subsequent run of my console app runs without issue. If I don't manually do that, I continuously get this error.
I'm running this console app on a build server that spawns fresh VMs from saved images on Azure, so I ultimately need to come up with some sort of programmatic way of making this work. I could also try modifying the machine image if this is fundamentally a permissions issue or something else like that, but I don't think it is.
I've eliminated the following possible sources of PerformanceCounter errors already:
- I scan to find the correct, unique name of the process if there are multiple instances running
- My console app runs with AnyCpu, with prefer 32-bit disabled
- I have run lodctr and do not have a corrupt performance counter registry AFAIK
- I destroy and recreate my counters upon exceptions
- And I cache my counter instances if they don't throw.
- I actually try running my application multiple times in a row to see if the process-specific instances get created after the app exits the first time.
- I exponentially back-off and wait a few seconds each time a counter fails to be recreated, in case the system needs more time to initialize them.
So I'm at a loss to explain how to fix this issue - any ideas on what the real underlying problem is?