C# – Why won’t the performance counters change

cperformancecounter

I must be doing something very wrong here. I create a custom performance counter as follows:

string counterCategory = "Test Category";
string counterName = "Test Counter";

if (!PerformanceCounterCategory.Exists(counterCategory))
{
    Console.WriteLine("Creating Counters");

    CounterCreationDataCollection counterCreationDataCollection =
        new CounterCreationDataCollection();

    counterCreationDataCollection.Add(
        new CounterCreationData(counterName,
        "Description",
        PerformanceCounterType.NumberOfItems32)
    );

    PerformanceCounterCategory.Create(counterCategory,
        "My category description/Help",
        PerformanceCounterCategoryType.SingleInstance,
        counterCreationDataCollection);
}

The counter category and counter are created and viewable in performance monitor.

I then attempt to change the value of the counter

PerformanceCounter myCounter = 
    new PerformanceCounter(counterCategory, counterName, false);

for (int i = 0; i < 10; i++)
{
    Console.WriteLine("Setting to "+i);
    myCounter.RawValue = i;
    Thread.Sleep(200);
}

myCounter.Close();

However as I sit and watch the counter in performance monitor nothing happens, the value never changes.

So what am I doing wrong?

If I add a call to nextValue(), or rawValue() the value from that is returned as I expected but the Windows Performance Monitor still shows a flat line, e.g.

for (int i = 0; i < 10; i++)
{
    Console.WriteLine("Setting to "+i);
    myCounter.IncrementValue()
    Console.WriteLine("Next Value = "+myCounter.RawValue()); 
    Thread.Sleep(200);
}

Edit: I've found that if I close the performance monitor and then reopen it without deleting the counters, that suddenly it realises there's a new value. So the values are being set, and persisting, however Performance Monitor doesn't see the changes.

Best Answer

A follow up is in order. It appears, under Win7 anyway, that the performance monitor may not work as expected. When I wrote the test code I paused the application after creating the counters, in order to start the performance monitor. Once I let it continue the monitor never changed it's counters, despite the underlying counter being changed.

If I then quit the performance monitor and restarted it the last counter value in the test program would be shown, indicating that it was being set correctly. If I then ran the test program again, just changing values, performance monitor would finally pick up the changes.

So the code, as everyone indicated is correct, it was the Windows Performance monitor that was misbehaving.

Thank you all for your answers!

Related Topic