C#准确获取系统 CPU 使用率

it2022-05-26  73

1.  PerformanceCounter 注意:(32位下不是线程安全的)

public class ProcessorUsage { const float sampleFrequencyMillis = 1000; protected object syncLock = new object(); protected PerformanceCounter counter; protected float lastSample; protected DateTime lastSampleTime; /// <summary> /// /// </summary> public ProcessorUsage() { this.counter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true); } /// <summary> /// /// </summary> /// <returns></returns> public float GetCurrentValue() { if ((DateTime.UtcNow - lastSampleTime).TotalMilliseconds > sampleFrequencyMillis) { lock (syncLock) { if ((DateTime.UtcNow - lastSampleTime).TotalMilliseconds > sampleFrequencyMillis) { lastSample = counter.NextValue(); lastSampleTime = DateTime.UtcNow; } } } return lastSample; } }

 

2.WMI

ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor"); var cpuTimes = searcher.Get() .Cast<managementobject>() .Select(mo => new { Name = mo["Name"], Usage = mo["PercentProcessorTime"] } ) .ToList(); var query = cpuTimes.Where(x => x.Name.ToString() == "_Total").Select(x => x.Usage); var cpuUsage = query.SingleOrDefault();

  

 

转载于:https://www.cnblogs.com/mschen/p/8031110.html

相关资源:C# 系统操作 实时显示CPU内存使用率

最新回复(0)