How to find the Number of CPU Cores in C#?


There are several different pieces of information relating to processors that we can get

  • Number of physical processors
  • Number of cores
  • Number of logical processors

These can all be different; in the case of a machine with 2 dual-core hyper-threadingenabled processors, there are 2 physical processors, 4 cores, and 8 logical processors.

The number of logical processors is available through the Environment class, but the other information is only available through WMI (and you may have to install some hotfixes or service packs to get it on some systems) −

Add a reference in your project to System.Management.dll In .NET Core, this is available (for Windows only) as a NuGet package.

Physical Processors

Example

class Program{
   public static void Main(){
      foreach (var item in new
      System.Management.ManagementObjectSearcher("Select * from
      Win32_ComputerSystem").Get()){
         Console.WriteLine("Number Of Physical Processors: {0} ",
         item["NumberOfProcessors"]);
      }
      Console.ReadLine();
   }
}

Output

Number Of Physical Processors: 1

Cores

class Program{
   public static void Main(){
      int coreCount = 0;
      foreach (var item in new
      System.Management.ManagementObjectSearcher("Select * from
      Win32_Processor").Get()){
         coreCount += int.Parse(item["NumberOfCores"].ToString());
      }
      Console.WriteLine("Number Of Cores: {0}", coreCount);
      Console.ReadLine();
   }
}

Output

Number Of Cores: 2

Logical Processors

class Program{
   public static void Main(){
      Console.WriteLine("Number Of Logical Processors: {0}",
      Environment.ProcessorCount);
      Console.ReadLine();
   }
}

Output

Number Of Logical Processors: 4

Updated on: 25-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements