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

我想使用下面的代码(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() + "%"; } } 

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方法之间建议的延迟时间是一秒,以允许计数器执行下一次增量读取。