C# 从性能计数器获取零

C# 从性能计数器获取零,c#,wcf,wmi,performancecounter,C#,Wcf,Wmi,Performancecounter,请参见下面的代码: PerformanceCounter total_cpu = new PerformanceCounter("Process", "% Processor Time", "_Total"); return total_cpu.NextValue(); //returns 0 它返回0 现在,看这个: PerformanceCounter total_cpu = new PerformanceCounter("Process", "% Proc

请参见下面的代码:

    PerformanceCounter total_cpu = new PerformanceCounter("Process", "% Processor Time", "_Total");
    return total_cpu.NextValue();
    //returns 0
它返回0

现在,看这个:

    PerformanceCounter total_cpu = new PerformanceCounter("Process", "% Processor Time", "_Total");
    while (true)
    {
        float t = total_cpu.NextValue();
        System.Threading.Thread.Sleep(1000);
        return t;
        //returns correct value (matched with Task Manager)
    }
我希望每隔2秒通过WCF服务连续获取性能计数器值(例如CPU使用率),结果将使用ajax显示在asp页面上

现在的问题是,正确的方法也会为自己创建一个循环。我试着用旗子来处理它,但没有帮助

注意:我也尝试了WMI,但没有返回正确的值


谢谢

对于许多计数器,第一个值始终为0。见文件备注部分的第一个注释:

您应该做的是让计数器的静态实例在后台每隔两秒读取一次,并将数据存储在您的服务可以获取的位置。每次请求时,您都可以返回预先获取的值,而不是每次都从计数器获取