How to find the Number of CPU Cores via .NET/C#?

2019-01-01 06:09发布

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

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

10条回答
明月照影归
2楼-- · 2019-01-01 06:57

It's rather interesting to see how .NET get this internally to say the least... It's as "simple" as below:

namespace System.Threading
{
    using System;
    using System.Runtime.CompilerServices;

    internal static class PlatformHelper
    {
        private const int PROCESSOR_COUNT_REFRESH_INTERVAL_MS = 0x7530;
        private static volatile int s_lastProcessorCountRefreshTicks;
        private static volatile int s_processorCount;

        internal static bool IsSingleProcessor
        {
            get
            {
                return (ProcessorCount == 1);
            }
        }

        internal static int ProcessorCount
        {
            get
            {
                int tickCount = Environment.TickCount;
                int num2 = s_processorCount;
                if ((num2 == 0) || ((tickCount - s_lastProcessorCountRefreshTicks) >= 0x7530))
                {
                    s_processorCount = num2 = Environment.ProcessorCount;
                    s_lastProcessorCountRefreshTicks = tickCount;
                }
                return num2;
            }
        }
    }
}
查看更多
妖精总统
3楼-- · 2019-01-01 06:57

One option would be to read the data from the registry. MSDN Article On The Topic: http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.localmachine(v=vs.71).aspx)

The processors, I believe can be located here, HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor

    private void determineNumberOfProcessCores()
    {
        RegistryKey rk = Registry.LocalMachine;
        String[] subKeys = rk.OpenSubKey("HARDWARE").OpenSubKey("DESCRIPTION").OpenSubKey("System").OpenSubKey("CentralProcessor").GetSubKeyNames();

        textBox1.Text = "Total number of cores:" + subKeys.Length.ToString();
    }

I am reasonably sure the registry entry will be there on most systems.

Though I would throw my $0.02 in.

查看更多
唯独是你
4楼-- · 2019-01-01 07:04

WMI queries are slow, so try to Select only the desired members instead of using Select *.

The following query takes 3.4s:

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())

While this one takes 0.122s:

foreach (var item in new System.Management.ManagementObjectSearcher("Select NumberOfCores from Win32_Processor").Get())
查看更多
素衣白纱
5楼-- · 2019-01-01 07:04

The the easyest way = Environment.ProcessorCount Exemple from Environment.ProcessorCount Property

    using System;

    class Sample 

{
    public static void Main() 
    {
    Console.WriteLine("The number of processors " +
        "on this computer is {0}.", 
        Environment.ProcessorCount);
    }
}
查看更多
登录 后发表回答