简体   繁体   中英

How to get number of CPU's logical cores/threads in C#?

How I can get number of logical cores in CPU?

I need this to determine how many threads I should run in my application.

使用Environment.ProcessorCount属性 ,它返回逻辑核心数。

You can get number of logical processors through the Environment class
number of cores:

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);

number of logical processors

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
}


Environment.ProcessorCount

 using System;

 class Sample 
 {
     public static void Main() 
     {
        Console.WriteLine("The number of processors on this computer is {0}.", 
           Environment.ProcessorCount);
     }
 }

go through this link http://msdn.microsoft.com/en-us/library/system.environment.processorcount.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM