views:

1753

answers:

3

Hi,

Is there a way via .NET/C# to find out the number of CPU cores?

Thanks!

PS This is a straight code question, not a "Should I use multi-threading?" question! :-)

+6  A: 
Environment.ProcessorCount

[Documentation]

280Z28
That's so beautifully simple I'm almost shedding tears. Thx for the reply!
Gregg Cleland
This gives the number of logical processors, not the number of cores.
CodeSavvyGeek
+2  A: 

Environment.ProcessorCount should give you the number of cores on the local machine.

Mithrax
As easy it can get. Thx for your reply!
Gregg Cleland
This gives the number of logical processors, not the number of cores.
CodeSavvyGeek
+6  A: 

There are several different pieces of information relating to processors that you could 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-threading-enabled 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):

Physical Processors:

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

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

Logical Processors:

Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount);

OR

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
}
CodeSavvyGeek
All Hail WMI! - that repository has almost everything =)
StingyJack
@StingyJack: True, but I wish it were in a nicer format. Discoverability is pretty low when you have to build raw string queries.
CodeSavvyGeek
WMI Code Creator will help with value discovery and query creation (it can even generate stubs in c#/vb.net).
StingyJack
Great info, thx. I've changed this as the accepted answer.
Gregg Cleland