views:

516

answers:

1

Here is my code snippet:

        PerformanceCounter cpuload = new PerformanceCounter();
        cpuload.CategoryName = "Processor";
        cpuload.CounterName = "% Processor Time";
        cpuload.InstanceName = "_Total";
        Console.WriteLine(cpuload.NextValue() + "%");

But the output is always 0%, while the cpuload.RawValue is like 736861484375 or so, what happened the NextValue()? My cpu is obviously in 0% usage.

Thanks guys~ 8^)

+2  A: 

The first iteration of he counter will always be 0, because it has nothing to compare to the last value. Try this:

var cpuload = new PerformanceCounter("Processor", "% Processor Time", "_Total");
Console.WriteLine(cpuload.NextValue() + "%");
Console.WriteLine(cpuload.NextValue() + "%");
Console.WriteLine(cpuload.NextValue() + "%");
Console.WriteLine(cpuload.NextValue() + "%");
Console.WriteLine(cpuload.NextValue() + "%");

Then you should see some data coming out. It's made to be seen in a constant graph or updated scenario...that's why you don't come across this problem often.

Here's the MSDN reference:

The method nextValue() always returns a 0 value on the first call. So you have to call this method a second time.

Nick Craver
Thanks, Buddy!!
smwikipedia