
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.
1static async Task Main(string[] args)
2{
3 CancellationToken token = new(); // optional external cancel
4
5 PerformanceCounter cpuCounter = new("Processor", "% Processor Time", "_Total");
6 using PeriodicTimer timer = new(TimeSpan.FromSeconds(1));
7
8 while (await timer.WaitForNextTickAsync(token) && !token.IsCancellationRequested)
9 {
10 Console.WriteLine(cpuCounter.NextValue());
11 }
12}
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.
Related articles

Jul 22, 2024 - 2 min read
.NET: the cost of returning an empty collection
Dealing with empty lists is an everyday situation in .NET. An empty list is often preferred to a null in order to control the logic. But how …

Jun 17, 2024 - 1 min read
.NET: use a preview version in your global.json
We are currently in the preview phase of .NET 9 , which releases in Nov 2024 - and if you want to test it extensively like I do, store the …

May 28, 2024 - 6 min read
Efficiently clean a string with .NET
Strings are one of the most commonly used types in .NET applications - and very often the source of inefficient code. For example, cleaning …
Let's Work Together
Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.
