我有以下类监视系统以查看我的程序使用的总 cpu 和系统的总 cpu 使用率。问题是有时,当我调用 GetHealthInformation 方法时,我的程序 % CPU 大于系统的 % CPU。这是我的代码:
public class MonitoringManager : AbstractComponent, IMonitoringManager, IStaticComponent {
private static PerformanceCounter totalCpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
private static PerformanceCounter cpuCounterMyProgram = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName);
private static DateTime lastUpdate = DateTime.UtcNow;
public void Load() {
cpuCounterMyProgram.NextValue();
totalCpuCounter.NextValue();
}
public HealthInfo GetHealthInformation(){
var now = DateTime.UtcNow;
if((now - lastUpdate).TotalMilliseconds <1000){
Thread.Sleep(1000);
}
lastUpdate = now;
return new HealthInfo(totalCpuCounter.NextValue(), cpuCounterMyProgram.NextValue() / Environment.ProcessorCount);
}
}
public class HealthInfo{
[DataMember]
public float CpuTotal { get; set; }
[DataMember]
public float CpuMyProgram { get; set; }
public HealthInfo(float cpuTotal, float cpuMyProgram){
CpuTotal = cpuTotal;
CpuMyProgram = cpuMyProgram;
}
#endregion IConstructors
}
}
怎么了?为什么有时系统的总 % CPU 是 0% 而我的程序是 2% ??