Reputation: 15
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?
Upvotes: 0
Views: 1376
Reputation: 386
Use the DispatcherTimer as stated in the below msdn and get the results as you needed.
Upvotes: 0
Reputation: 1649
First of all the
float cpuPercent = getCPUValue();
line should be inside the loop. Otherwise you will read the CPU usage only once. and will iterate over the same value.
You should create Only one PerformanceCounter object, and just call cpuCounter.NextValue() again and again inside the loop. DON'T create the same CPU PerformanceCounter in every iteration.
PerformanceCounter counter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
while (true)
{
float cpuPercent = counter.nextValue();
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;
}
}
As stated in MSDN
To obtain performance data for counters that required an initial or previous value for performing the necessary calculation, call the NextValue method twice and use the information returned as your application requires.
So you should call the cpuCounter.NextValue() twice (with about a 1 second delay between the calls) to start getting correct CPU Usage results.
BTW, You should wait about a 1 second between each read operation from the CPU PerformanceCounter (to ensure update).
As shown in this post Retriving Accurate CPU Usate In C#
Upvotes: 1