在asp.net框架中使用c#获取当前cpu使用情况 [英] get current cpu usage using c# in asp.net framework

查看:86
本文介绍了在asp.net框架中使用c#获取当前cpu使用情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to find out the current CPU usage using the codes below(c# in asp.net framework). However it gives me "0% of CPU usage" when I try to run the program. When I check my task manager, I found out that the actual total CPU usage is more than 5%. Does anyone know what is wrong with the code below?

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 .您将需要一个 Timer Thread 来在后台持续监视该值.例如,此代码将每秒输出正确的值(不要使用此实际代码,因为它又快又脏):

The first value returned by a PerformanceCounter will always be 0. You'll need a Timer or Thread that keeps monitoring the value in the background. This code for example will output the correct value every second (don't use this actual code, it's quick and dirty):

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 方法:

Make sure to read the remarks of the PerformanceCounter.NextValue method:

如果计数器的计算值取决于两次计数器读取,则第一次读取操作将返回0.0.重置性能计数器属性以指定其他计数器等效于创建新的性能计数器,并且使用新属性进行的第一次读取操作将返回0.0.建议两次调用NextValue方法之间的延迟时间为一秒,以允许计数器执行下一个增量读取.

If the calculated value of a counter depends on two counter reads, the first read operation returns 0.0. Resetting the performance counter properties to specify a different counter is equivalent to creating a new performance counter, and the first read operation using the new properties returns 0.0. The recommended delay time between calls to the NextValue method is one second, to allow the counter to perform the next incremental read.

这篇关于在asp.net框架中使用c#获取当前cpu使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆