Question

So I'm working on something that checks the CPU Usage under a certain percentage so that it doesn't bog down the system. I have this code:

 static PerformanceCounter cpuUsage;

    public static void Main(string[] args)


    {
        cpuUsage = new PerformanceCounter("Processor", "% Processor Time", "_Total");


        do
        {

            Console.WriteLine(cpuUsage.NextValue() + " %");
            Thread.Sleep(1000);

            Console.WriteLine(cpuUsage.NextValue() + " %");
        }

        while (cpuUsage.NextValue() < 50.00);

    }

My original thought was to use this do while loop to keep checking the CPU Usage until it went over 50% then stop the loop. But for some reason even if the cpuUsage.NextValue is over 50 it still doesn't exit the loop. I'm guessing it is some problem with this value. Any suggestions?

Was it helpful?

Solution

I think the clue is in the 0% output - the documentation recommends you only call NextValue every second so that it has time to get data, but you're actually calling it 3 times every second. Try:

float usage;
do {
     Thread.Sleep(TimeSpan.FromSeconds(1));
     usage = cpuUsage.NextValue();
     Console.WriteLine(usage + " %");
} while (usage < 50.00);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top