Why don't my performance counters change?

I have to do something very bad here. I create a special 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 displayed in the performance monitor.

Then I try to change the counter value

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, when I sit and look at the counter in the performance monitor, nothing happens, the value never changes.

So what am I doing wrong?

If I add a call to nextValue () or rawValue (), a value that returns as I expected, but the Windows performance monitor still shows a flat line, for example

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

: , , , , . , Performance Monitor .

+5
3

. -, Win7 , , . , , . , , .

, , . , , , , .

, , , , Windows, .

!

+2

? , - , , , .

, , Performance Monitor.

+1

Your code looks good. From my working example, the only difference is that I call the increment method after setting RawValue.

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

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

myCounter.Close();
0
source

All Articles