【发布时间】:2018-02-05 18:04:38
【问题描述】:
我总是使用这个简单的代码(来自#278071)来获取 CPU 使用率:
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
public string getCurrentCpuUsage() {
return cpuCounter.NextValue()+"%";
}
它多年来一直运行良好。但是升级后就不行了。我现在使用的是 Windows 10,cpuCounter.NextValue 抛出 System.FormatException:输入字符串格式不正确。
怎么了?是因为Windows 10吗?还是因为我的新 CPU - Xeon E5-2683?如何获取 CPU 使用率?
更新: 使用 .NET Framework 3.5 时引发 System.FormatException。我切换到 .NET Framework 4.5,现在它抛出 InvalidOperationException: Cannot load Counter Name data because an invalid index '' was read from the registry.
【问题讨论】:
-
抛出错误的是
cpuCounter.NextValue(),还是cpuCounter.NextValue()+"%"? -
cpuCounter.NextValue(); cpuCounter.NextSample() 也会抛出异常。
-
在我的win10机器上工作,所以可能不是这样。代码看起来不错。
-
你链接的问题是 10 岁。链接答案中的链接指向 .Net 2.0 版的文档。您的 .Net 版本是什么?你能在相应的文档版本中检查你的答案吗?
-
刚刚更新的问题。
标签: c# .net cpu-usage performancecounter formatexception