2017-08-28 214 views
1

我一直用这个简单的代码(从#278071)获得CPU使用率:无法获得在C#中使用的PerformanceCounter CPU占用率 - System.FormatException

var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); 

public string getCurrentCpuUsage() { 
     return cpuCounter.NextValue()+"%"; 
} 

它完美地工作多年。但升级后不起作用。我正在使用Windows 10并且cpuCounter.NextValue抛出System.FormatException:输入字符串的格式不正确。

怎么了?是因为Windows 10吗?或者是因为我的新CPU - 至强E5-2683?我如何获得CPU使用率?

upd: 当我使用.NET Framework 3.5时,会引发System.FormatException。我切换到.NET Framework 4.5,现在抛出InvalidOperationException:无法加载计数器名称数据,因为从注册表中读取了无效索引''。

+0

是'cpuCounter.NextValue()'抛出错误,或'cpuCounter.NextValue()+“%”'? – crashmstr

+0

cpuCounter.NextValue(); cpuCounter.NextSample()也会抛出异常。 – Cluster

+0

适用于我的win10机器,因此可能不是这样。代码看起来很好。 –

回答