I mainly followed what was discussed in the second answer to this thread. I want to run a program that will continuously check for CPU usage above 5% for 10 seconds and alert me every time it happens.
How to get the CPU Usage in C#?
And my code is as follows:
static void Main(string[] args)
{
    Console.WriteLine("Checking for CPU usage");
    int totalhits = 0;
    float cpuPercent = getCPUValue();
    while (true)
    {
        if (cpuPercent >= 5)
        {
            totalhits += 1;
            if (totalhits == 10)
            {
                Console.WriteLine("Alert Usage has exceeded");
                Console.WriteLine("Press Enter to continue");
                Console.ReadLine();
                totalhits = 0;
            }
        }
        else
        {
            totalhits = 0;
        }
    }
}
private static float getCPUValue()
{
    PerformanceCounter cpuCounter = new PerformanceCounter();
    cpuCounter.CategoryName = "Processor";
    cpuCounter.CounterName = "% Processor time";
    cpuCounter.InstanceName = "_Total";
    float firstValue = cpuCounter.NextValue();
    System.Threading.Thread.Sleep(50);
    float secondValue = cpuCounter.NextValue();
    return secondValue;
}
My problem is that it never hits that threshold and if I take out the totalhits = 0; statement inside the innermost if statement then it hits the threshold in less than 5 seconds.
What am I doing wrong?
 
     
     
    