我有以下类来监视系统,以查看我的程序使用的总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%?