If you are doing any sort of parallel work, perhaps using Parallel.ForEach, Parallel.For, Parallel.Invoke or just a collection of plain old Task objects, you will might want to know how many CPUs are available.

The same would apply for the async equivalents - Parallel.ForAsync and Parallel.ForEachAsync

This is available via the ProcessorCount property of the Environment class.

var processorCount = Environment.ProcessorCount;

Console.WriteLine($"There are {processorCount} processors available on this machine");

This prints the following on my console:

There are 16 processors available on this machine

If I verify this empirically:

CPUs

Which tallies with the result.

Notably, if the underlying machine has CPUs with multiple cores, this count is the result that will be returned.

Additionally, this number is determined at the application’s start. If it subsequently changes - perhaps it is a virtualized environment that allows the change at runtime, or native hardware with hot-swappable CPUs, the count will not be updated.

TLDR

The Environment.ProcessorCount property will return the number of CPUs (or CPU cores) available to your application.

Happy hacking!