一、解决方案
1、Windows:可以通过 PerformanceCounter 获取系统性能数据:CPU 使用率、内存使用情况等
**注意:** 在.netcore版本中系统不在自带System.Diagnostics命名空间需要单独引入nuget包System.Diagnostics.PerformanceCounter
2、Linux:可以通过 /proc/stat 或使用 sysctl 命令来获取 CPU 使用率。
二、代码实现
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace ConsoleApp2
{
internal class Program
{
static void Main(string[] args)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
GetWindowsCpuUsage();
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
GetLinuxCpuUsage();
}
else
{
Console.WriteLine("当前平台不支持获取 CPU 使用率。");
}
}
static void GetWindowsCpuUsage()
{
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
cpuCounter.NextValue(); // 获取初始值
System.Threading.Thread.Sleep(1000); // 等待 1 秒钟
float cpuUsage = cpuCounter.NextValue();
Console.WriteLine($"Windows CPU 使用率: {cpuUsage}%");
}
static void GetLinuxCpuUsage()
{
string[] lines = File.ReadAllLines("/proc/stat");
var cpuLine = lines.FirstOrDefault(line => line.StartsWith("cpu "));
if (cpuLine != null)
{
var cpuStats = cpuLine.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Skip(1)
.Select(int.Parse)
.ToArray();
int user = cpuStats[0];
int nice = cpuStats[1];
int system = cpuStats[2];
int idle = cpuStats[3];
int iowait = cpuStats[4];
int irq = cpuStats[5];
int softirq = cpuStats[6];
int steal = cpuStats[7];
int guest = cpuStats[8];
int guestNice = cpuStats[9];
int totalIdle = idle + iowait;
int totalNonIdle = user + nice + system + irq + softirq + steal;
int totalCpu = totalIdle + totalNonIdle;
float cpuUsage = (totalNonIdle / (float)totalCpu) * 100;
Console.WriteLine($"Linux CPU 使用率: {cpuUsage:F2}%");
}
else
{
Console.WriteLine("无法获取 CPU 数据。");
}
}
}
}
实现以上方法即可获取不同操作系统的CPU使用率!!!