.net核心CPU使用率

时间:2019-12-24 07:17:04

标签: c# .net .net-core

我最近从c#迁移到.net core。在c#中,我使用以下命令获取CPU使用率:

PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;

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

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

但是在.net核心PerformanceCounter中不可用,解决方案是什么?请给我一个建议。

1 个答案:

答案 0 :(得分:1)

性能计数器不在Linux中,因此不在NET Core中。替代方式:

private async Task<double> GetCpuUsageForProcess()
{
    var startTime = DateTime.UtcNow;
    var startCpuUsage = Process.GetProcesses().Sum(a => a.TotalProcessorTime.TotalMilliseconds);
    await Task.Delay(500);

    var endTime = DateTime.UtcNow;
    var endCpuUsage = Process.GetProcesses().Sum(a => a.TotalProcessorTime.TotalMilliseconds);
    var cpuUsedMs = endCpuUsage - startCpuUsage;
    var totalMsPassed = (endTime - startTime).TotalMilliseconds;
    var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed);
    return cpuUsageTotal * 100;
}