0

I've already found this question telling that the first occurrence of my PerformanceCounter is 0, so I have to call it multiple times to get the right result.

I got that to work fine - it looks like this:

public static float GetCpuUsage()
{
    var cpuCounter = new PerformanceCounter();

    cpuCounter.CategoryName = "Processor";
    cpuCounter.CounterName = "% Processor Time";
    cpuCounter.InstanceName = "_Total";

    // Prime it
    cpuCounter.NextValue();

    Thread.Sleep(500);

    return cpuCounter.NextValue();
}

However, I wish to be able to get the result from more than one PerformanceCounter without having to wait half a second for each one. I did it like this:

public static float GetCpuUsage(PerformanceCounter counter)
{
    if (counter == null)
    {
        counter = new PerformanceCounter();
        counter.CategoryName = "Processor";
        counter.CounterName = "% Processor Time";
        counter.InstanceName = "_Total";
    }

    return counter.NextValue();
}

And I call it like this:

PerformanceCounter cpuCounter = null;
PerformanceCounter memoryCounter = null;

while (_isRunning)
{
    result.Cpu = GetCpuUsage(cpuCounter);
    result.Memory = GetAvailableMemory(memoryCounter);

    // Process result

    Thread.Sleep(500);
}

I thought that was a pretty good idea - passing the same counter instance to the method every time.

However, it doesn't actually work, cpu is always 0.

It tells me there is something basic about PerformanceCounters I don't understand (and that is not addressed in the question I linked to).

What exactly is it that makes the PerformanceCounter work? Because it seems that waiting for 500 milliseconds between each NextValue call is not the only difference.

4

1 に答える 1