在asp.net框架中使用c#获取当前CPU使用情况

本文关键字:CPU 情况 用情 获取 net asp 框架 | 更新日期: 2023-09-27 18:07:09

我想使用下面的代码(asp.net框架中的c#)找出当前的CPU使用情况。然而,当我尝试运行该程序时,它给了我"0%的CPU使用率"。当我检查任务管理器时,我发现实际的总CPU使用率超过了5%。有人知道下面的代码有什么问题吗?

public partial class cpuUsage : System.Web.UI.Page
{
    PerformanceCounter cpu;
    protected void Page_Load(object sender, EventArgs e)
    {   
        cpu = new PerformanceCounter();
        cpu.CategoryName = "Processor";
        cpu.CounterName = "% Processor Time";
        cpu.InstanceName = "_Total";
        lblCPUUsage.Text = getCurrentCpuUsage();
    }
    public string getCurrentCpuUsage()
    {
        return cpu.NextValue() + "%";
    }
}

在asp.net框架中使用c#获取当前CPU使用情况

PerformanceCounter返回的第一个值始终是0。您将需要一个TimerThread来保持监视后台的值。例如,下面的代码将每秒输出正确的值(不要使用实际的代码,它又快又脏):

new Thread(() =>
{
    var cpu = new PerformanceCounter
    {
        CategoryName = "Processor",
        CounterName = "% Processor Time",
        InstanceName = "_Total"
    }
    while (true)
    {
        Debug.WriteLine("{0:0.0}%", cpu.NextValue());
        Thread.Sleep(1000);
    }
}).Start();

请务必阅读PerformanceCounter.NextValue方法的注释:

如果计数器的计算值依赖于两次读取计数器,则第一次读取操作返回0.0。重置性能计数器属性以指定不同的计数器相当于创建一个新的性能计数器,并且使用新属性的第一个读取操作返回0.0。建议调用NextValue方法之间的延迟时间为1秒,以允许计数器执行下一个增量读取。