如何在c#中持续检查CPU使用情况

本文关键字:CPU 检查 用情 情况 | 更新日期: 2023-09-27 18:09:52

我主要遵循这个帖子的第二个答案中讨论的内容。我想运行一个程序,它将连续检查CPU使用率超过5%,持续10秒,并在每次发生时提醒我。

如何在c#中获得CPU使用率?

我的代码如下:

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;语句,然后在不到5秒的时间内达到阈值。

我做错了什么?

如何在c#中持续检查CPU使用情况

首先

float cpuPercent = getCPUValue();

行应该在循环内。否则,您将只读取一次CPU使用率。并将迭代相同的值。

你应该只创建一个PerformanceCounter对象,并且在循环中一次又一次地调用cpuCounter.NextValue()。不要在每次迭代中创建相同的CPU PerformanceCounter。

   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;
       }
   }

如MSDN

所述

要获取需要初始值或先前值来执行必要计算的计数器的性能数据,请调用NextValue方法两次,并根据应用程序的需要使用返回的信息。

所以你应该调用两次cpuccounter . nextvalue()(调用之间大约有1秒的延迟)来开始得到正确的CPU使用结果。

BTW,您应该在CPU PerformanceCounter的每个读取操作之间等待大约1秒(以确保更新)。

如本文所示,在c#中检索准确的CPU使用率

使用下面msdn中所述的DispatcherTimer,并根据需要获得结果。

DispatcherTimer