C# 为什么cpu性能计数器一直报告0%的cpu使用率?

C# 为什么cpu性能计数器一直报告0%的cpu使用率?,c#,cpu-usage,performancecounter,C#,Cpu Usage,Performancecounter,输出始终为0%,而cpuload.RawValue类似于736861484375左右,在NextValue()?计数器的第一次迭代将始终为0,因为它与最后一个值没有任何可比性。试试这个: PerformanceCounter cpuload = new PerformanceCounter(); cpuload.CategoryName = "Processor"; cpuload.CounterName = "% Processor Time"; cpuload.InstanceName =

输出始终为0%,而
cpuload.RawValue
类似于736861484375左右,在
NextValue()

计数器的第一次迭代将始终为0,因为它与最后一个值没有任何可比性。试试这个:

PerformanceCounter cpuload = new PerformanceCounter();
cpuload.CategoryName = "Processor";
cpuload.CounterName = "% Processor Time";
cpuload.InstanceName = "_Total";
Console.WriteLine(cpuload.NextValue() + "%");
然后你会看到一些数据出来。它是在一个恒定的图形或更新的场景中显示的…这就是为什么您不会经常遇到这个问题

以下是:

方法nextValue()总是返回 第一次调用的值为0。那么你呢 必须再次调用此方法 时间


第一次检索第一个值(将为0)

然后等待1000毫秒

NextValue();
然后检索第二个值,它是真实的cpu使用率

Thread.Sleep(1000);
代码应该如下所示:

NextValue();
NextValue();
float perfCounterValue = perfCounter.NextValue();

//Thread has to sleep for at least 1 sec for accurate value.
System.Threading.Thread.Sleep(1000);

perfCounterValue = perfCounter.NextValue();

Console.WriteLine("Value: {0}", perfCounterValue);