我通过在线示例开发了以下代码示例,但没有给出CPU使用率的百分比。
PerformanceCounter RcpuCounter;
PerformanceCounter RramCounter;
public void ResourcesCPU()
{
RcpuCounter = new PerformanceCounter();
RcpuCounter.CategoryName = "Processor";
RcpuCounter.CounterName = "% Processor Time";
RcpuCounter.InstanceName = "_Total";
string cpu = getCurrentCpuUsage();
}
public string getCurrentCpuUsage()
{
string Value1 = RcpuCounter.NextValue() + "%";
return Value1;
}
然后,我如下更改了getCurrentCpuUsage()方法,它给了我一个CPU使用率的值。
public string getCurrentCpuUsage()
{
string Value1 = RcpuCounter.NextValue() + "%";
Thread.Sleep(500);
string Value2 = RcpuCounter.NextValue() + "%";
return Value2;
}
我知道有可能在不同的时间使用不同的cpu,但是我的问题是为什么第一个算法没有给我任何价值。
答案是在MSDN中:
如果计数器的计算值取决于两次计数器读取,则第一次读取操作将返回0.0。重置性能计数器属性以指定其他计数器等效于创建新的性能计数器,并且使用新属性进行的第一次读取操作将返回0.0。建议两次调用NextValue方法之间的延迟时间为一秒,以允许计数器执行下一个增量读取。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句