Read cpu load on Windows with .NET
In C# (.NET 6 and above), there is now a very simple way to read out the CPU load with minimal overhead - i.e. without threads. The PerformanceCounter from the System.Diagnostics
namespace helps us with this.
static async Task Main(string[] args)
{
CancellationToken token = new(); // optional external cancel
PerformanceCounter cpuCounter = new("Processor", "% Processor Time", "_Total");
using PeriodicTimer timer = new(TimeSpan.FromSeconds(1));
while (await timer.WaitForNextTickAsync(token) && !token.IsCancellationRequested)
{
Console.WriteLine(cpuCounter.NextValue());
}
}
Hint: the first query of the CPU values always returns 0.0. This is also specified accordingly in the documentation: If the calculated value of a counter depends on two counter reads, the first read operation returns 0.0.