Updated on
Environment.ProcessorCount gives us the number of logical processors our process can use, and it works on every platform .NET runs on. For physical cores and processor sockets, we query WMI on Windows through the System.Management package.
Knowing the difference matters when we size parallel work. A six-core CPU with two threads per core reports 12 logical processors, even though it has 6 cores.
Let’s start.
What Does Environment.ProcessorCount Return?
Environment.ProcessorCount returns the number of logical processors our process can use, not the number of cores. On our test machine, one six-core CPU with two threads per core, it returns 12.
Microsoft Learn describes the property as the number of “processors available to the current process”. On Linux and macOS, and on Windows since .NET 6, the runtime takes the smallest of three values: the logical processors on the machine, the processors the process is pinned to through CPU affinity, and a CPU usage limit rounded up to a whole number.
So with a CPU usage limit of two CPUs, we get 2, even on a 64-core host.
The runtime reads the value once at startup, and it doesn’t change while the process runs. It needs no package and works on every platform .NET supports. For physical cores or sockets, we have to ask the operating system, and on Windows that means WMI.
We begin with the simplest way, to retrieve the amount of logical processors:
var cpuCount = Environment.ProcessorCount;
This one line is all we need for the logical processor count, and it’s the only approach in this article that works on Windows, Linux and macOS alike. The other methods below rely on Windows APIs.
There are three different terms for CPU core count. There are physical processors, CPU cores, and logical processors. They differ in the amount and therefore have different meanings.
Physical processors represent the tangible chips installed on the motherboard, each containing CPU cores capable of executing instructions independently. Logical processors, on the other hand, are virtual entities generated by technologies like hyper-threading. With it, each core can handle multiple threads concurrently. Often the number of logical processors is double the number of cores.
How Do We Get the Number of Physical Cores in C#?
On Windows, we get physical cores from WMI (Windows Management Instrumentation), the operating system’s standard interface for hardware, software and configuration data. The System.Management NuGet package gives us the ManagementObjectSearcher class, which runs a WMI query and returns one object per result.
Two WMI classes cover everything we need. Win32_Processor returns one object per physical processor, each with its own NumberOfCores, so we add them up to get the total. Win32_ComputerSystem returns a single object with NumberOfProcessors, the count of physical processors, and NumberOfLogicalProcessors.
On our test machine, the three queries return 6 cores, 1 physical processor and 12 logical processors.
WMI exists only on Windows, though, and many servers run Linux, so a library that depends on it can’t be used or tested everywhere. That’s why every method below checks OperatingSystem.IsWindows() first and throws a PlatformNotSupportedException anywhere else.
First of all, we add the System.Management NuGet package to our project:
dotnet add package System.Management
Each method in this section lives in a CpuInformation class. The class holds the WMI query that two of the methods share, and the using lines the rest of the article needs:
using System.Management;
using System.Runtime.InteropServices;
namespace RetrievalOfCpuCores;
public class CpuInformation
{
const string wmiQuery = "Select * from Win32_ComputerSystem";
}
With that, let’s look at how we retrieve the number of cores.
Retrieve the Number of Cores
Now we can retrieve the number of cores:
public int GetNumberOfCores()
{
if (!OperatingSystem.IsWindows())
{
throw new PlatformNotSupportedException();
}
var coreCount = 0;
using var searcher = new ManagementObjectSearcher("Select * from Win32_Processor");
foreach (var item in searcher.Get())
{
coreCount += Convert.ToInt32(item["NumberOfCores"]);
}
return coreCount;
}
Here, we define the GetNumberOfCores() method. If the platform is not Windows, we throw a PlatformNotSupportedException. Otherwise, we continue to count the total number of cores. We cover OperatingSystem.IsWindows() and its siblings in our article on how to determine the operating system in C#.
The ManagementObjectSearcher class is the WMI API that we use to query for the Windows system information. We loop over the query result and retrieve the NumberOfCores property from each WMI instance. WMI returns the value as a uint, so Convert.ToInt32() turns it into an int without a round trip through a string. ManagementObjectSearcher derives from Component, so it is IDisposable, and we dispose of it with a using declaration.
Physical Processors
We can also get the number of physical processors:
public int GetPhysicalProcessors()
{
if (!OperatingSystem.IsWindows())
{
throw new PlatformNotSupportedException();
}
using var searcher = new ManagementObjectSearcher(wmiQuery);
foreach (var item in searcher.Get())
{
return Convert.ToInt32(item["NumberOfProcessors"]);
}
return 0;
}
Here, we loop over the results of the query Select * from Win32_ComputerSystem, which returns a single object for the machine. We read its NumberOfProcessors property, the count of physical processors in the system, and return it.
Logical Processors
Instead of using the Environment.ProcessorCount we can also use this API to get the number of logical processors:
public int GetLogicalProcessors()
{
if (!OperatingSystem.IsWindows())
{
throw new PlatformNotSupportedException();
}
using var searcher = new ManagementObjectSearcher(wmiQuery);
foreach (var item in searcher.Get())
{
return Convert.ToInt32(item["NumberOfLogicalProcessors"]);
}
return 0;
}
Similar to our previous method, we use a loop to get the results from the ManagementObjectSearcher class. This time, we retrieve the NumberOfLogicalProcessors property, representing the count of logical processors in the system.
This is the machine’s count. By Microsoft Learn’s definition, Environment.ProcessorCount can be lower when the process runs with CPU affinity or a CPU limit.
Processors Excluded From Windows
Windows doesn’t always use every processor in the machine. A boot setting can tell it to start with fewer. The bcdedit documentation describes its numproc option plainly: “Uses only the specified number of processors.”
To dig deeper into processor exclusions, we can use Windows API calls available in setupapi.dll. These calls let us count every processor device Windows has detected. We first need to create some functions and structures:
[DllImport("setupapi.dll", SetLastError = true)]
private static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid,
[MarshalAs(UnmanagedType.LPStr)] string enumerator,
IntPtr hwndParent,
int Flags);
[DllImport("setupapi.dll", SetLastError = true)]
private static extern int SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);
[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet,
int MemberIndex,
ref SP_DEVINFO_DATA DeviceInterfaceData);
[StructLayout(LayoutKind.Sequential)]
private struct SP_DEVINFO_DATA
{
public int cbSize;
public Guid ClassGuid;
public uint DevInst;
public IntPtr Reserved;
}
private enum DIGCF
{
DEFAULT = 0x1,
PRESENT = 0x2,
ALLCLASSES = 0x4,
PROFILE = 0x8,
DEVICEINTERFACE = 0x10,
}
Here, we include imports (DllImport) for functions from setupapi.dll, a structure (SP_DEVINFO_DATA), and an enumeration (DIGCF). These are the functions and types we need to count the processor devices. Like the WMI methods, they go inside the CpuInformation class.
Now, we count all the processor devices:
public int GetLogicalProcessorsIncludingExcluded()
{
if (!OperatingSystem.IsWindows())
{
throw new PlatformNotSupportedException();
}
var deviceCount = 0;
var deviceList = IntPtr.Zero;
var processorGuid = new Guid("{50127dc3-0f36-415e-a6cc-4cb3be910b65}");
try
{
deviceList = SetupDiGetClassDevs(ref processorGuid, "ACPI", IntPtr.Zero, (int)DIGCF.PRESENT);
for (var deviceNumber = 0; ; deviceNumber++)
{
var deviceInfo = new SP_DEVINFO_DATA();
deviceInfo.cbSize = Marshal.SizeOf(deviceInfo);
if (!SetupDiEnumDeviceInfo(deviceList, deviceNumber, ref deviceInfo))
{
deviceCount = deviceNumber;
break;
}
}
}
finally
{
if (deviceList != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceList); }
}
return deviceCount;
}
Here, we define the GetLogicalProcessorsIncludingExcluded() method, which counts the processor devices on a Windows system using SetupApi calls.
We start by initializing variables and fetching device information using the SetupDiGetClassDevs() method. Then we enumerate through the devices and update the count. Finally, we clean up resources and return the count of processors.
To see whether Windows has detected more processor devices than the logical processors WMI reports, we subtract one count from the other:
public int GetExcludedProcessors()
{
return GetLogicalProcessorsIncludingExcluded() - GetLogicalProcessors();
}
Both methods throw on Linux and macOS, so this one does too.
Let’s call every method from Program.cs:
using RetrievalOfCpuCores;
CpuInformation cpuInformation = new();
Console.WriteLine("Processors Count: {0}", Environment.ProcessorCount);
Console.WriteLine("Logical Processors: {0}", cpuInformation.GetLogicalProcessors());
Console.WriteLine("Number Of Cores: {0}", cpuInformation.GetNumberOfCores());
Console.WriteLine("Physical Processors: {0}", cpuInformation.GetPhysicalProcessors());
Console.WriteLine("Logical Processors (including excluded Processors): {0}", cpuInformation.GetLogicalProcessorsIncludingExcluded());
Console.WriteLine("Excluded Processors: {0}", cpuInformation.GetExcludedProcessors());
On our test machine, a single six-core CPU with hyper-threading, the output is:
Processors Count: 12 Logical Processors: 12 Number Of Cores: 6 Physical Processors: 1 Logical Processors (including excluded Processors): 12 Excluded Processors: 0
The machine has one chip with six cores and twelve logical processors, and the device count matches the logical count, so the last line reads 0. We haven’t run this on a machine with numproc set, so we can’t show that line above zero.
Application and Optimization
Multithreading is one way to speed up a program, and the processor count tells us how far it can go. For CPU-bound work, the processor count is how many threads can run at the same moment, so threads beyond it wait their turn.
So for CPU-bound loops, Environment.ProcessorCount makes a sensible cap on how many items run at once:
var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };
Parallel.For(0, 4, options, i => Console.WriteLine("Work item {0} done", i));
The work items finish in whatever order the threads get to them, so the output order changes from run to run.
We don’t always need the cap. Microsoft’s documentation says we usually don’t have to change this setting, because Parallel.For already uses the threads the scheduler gives it. We set it when several parallel jobs share the machine, or when the loop body runs long enough to confuse the thread pool. For I/O-bound work, the processor count says very little, and we have to measure. We go deeper into that in our article on Parallel.ForEachAsync and Task.Run with Task.WhenAll.
CPU optimization is still a balance between performance and power efficiency. Using every processor can make a job finish sooner, but it also keeps the whole CPU busy while it runs.
Conclusion
We’ve covered the three counts a machine reports: physical processors, cores and logical processors. Environment.ProcessorCount gives us the logical processors our process can use on any platform, and on Windows, WMI adds the cores and the physical processors. SetupAPI adds a count of every processor device Windows has detected.
When we size parallel work, the number to reach for is Environment.ProcessorCount, because, as Microsoft Learn describes it, it already accounts for affinity and CPU limits. The WMI numbers describe the hardware, and our process may be allowed to use less of it.
Tested with .NET 11 (SDK 11.0.100, runtime 11.0.0) and System.Management 11.0.0 on Windows.
