如何在C#中获取CPU的逻辑内核/线程数?

时间:2012-10-22 16:35:40

标签: c# multithreading .net-3.5

如何在CPU中获取多个逻辑核心?

我需要这个来确定我应该在应用程序中运行多少个线程。

2 个答案:

答案 0 :(得分:23)

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

答案 1 :(得分:17)

您可以通过Environment类获取多个逻辑处理器 核心数量:

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

逻辑处理器的数量

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

浏览此链接http://msdn.microsoft.com/en-us/library/system.environment.processorcount.aspx