【发布时间】:2014-08-13 18:58:19
【问题描述】:
我主要遵循该线程的第二个答案中讨论的内容。我想运行一个程序,它会在 10 秒内持续检查 CPU 使用率是否超过 5%,并在每次发生时提醒我。
How to get the CPU Usage in C#?
而我的代码如下:
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;
}
我的问题是它永远不会达到那个阈值,如果我取出 totalhits = 0;最里面的 if 语句中的语句,那么它会在不到 5 秒的时间内达到阈值。
我做错了什么?
【问题讨论】:
-
float cpuPercent = getCPUValue();应该在你的循环内..
-
您正在获取 CPU 百分比,然后在循环中旋转,永远检查。此外,每个循环迭代不是“1 秒”,您需要让线程休眠以模拟类似的东西。