有没有办法可靠地检测CPU核心的总数?

Joh*_*res 7 .net c# multithreading cpu-cores

我需要一种可靠的方法来检测计算机上有多少CPU核心.我正在创建一个数字密集的模拟C#应用程序,并希望创建最大数量的运行线程作为核心.我已经尝试了许多围绕互联网建议的方法,比如Environment.ProcessorCount,使用WMI,这段代码:http://blogs.adamsoftware.net/Engine/DeterminingthenumberofphysicalCPUsonWindows.aspx 他们似乎都不认为AMD X2有两个内核.有任何想法吗?

编辑:似乎Environment.ProcessorCount返回正确的数字.它位于具有超线程的英特尔CPU上,返回错误的数字.超线程的核心是2,当它应该只有1时.

Sam*_*ell 7

据我所知,Environment.ProcessorCount在WOW64下运行时可能会返回一个不正确的值(作为64位操作系统上的32位进程),因为它依赖的P/Invoke签名GetSystemInfo代替使用GetNativeSystemInfo.这似乎是一个明显的问题,所以我不确定为什么它不会在这一点上得到解决.

试试这个,看看它是否解决了这个问题:

private static class NativeMethods
{
    [StructLayout(LayoutKind.Sequential)]
    internal struct SYSTEM_INFO
    {
        public ushort wProcessorArchitecture;
        public ushort wReserved;
        public uint dwPageSize;
        public IntPtr lpMinimumApplicationAddress;
        public IntPtr lpMaximumApplicationAddress;
        public UIntPtr dwActiveProcessorMask;
        public uint dwNumberOfProcessors;
        public uint dwProcessorType;
        public uint dwAllocationGranularity;
        public ushort wProcessorLevel;
        public ushort wProcessorRevision;
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    internal static extern void GetNativeSystemInfo(ref SYSTEM_INFO lpSystemInfo);
}

public static int ProcessorCount
{
    get
    {
        NativeMethods.SYSTEM_INFO lpSystemInfo = new NativeMethods.SYSTEM_INFO();
        NativeMethods.GetNativeSystemInfo(ref lpSystemInfo);
        return (int)lpSystemInfo.dwNumberOfProcessors;
    }
}
Run Code Online (Sandbox Code Playgroud)


nbe*_*ans 2

请参阅检测处理器数量

或者,使用GetLogicalProcessorInformation()Win32 API:http://msdn.microsoft.com/en-us/library/ms683194 (VS.85).aspx