Getting the total number of processors a computer has (c#)
- by mbcrump
Here is a code snippet for getting the total number of processors a computer has without using Environment.ProcessorCount. I found out that Environment.ProcessorCount is not necessary returning the correct value on some Intel based CPU’s. using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Globalization; usingSystem.Runtime.InteropServices; namespaceConsoleApplication4 { classProgram { static voidMain(string[] args) { int c = ProcessorCount; Console.WriteLine("The computer has {0} processors", c); Console.ReadLine(); } private static classNativeMethods { [StructLayout(LayoutKind.Sequential)] internal struct SYSTEM_INFO { public ushort wProcessorArchitecture; public ushort wReserved; public uint dwPageSize; publicIntPtr lpMinimumApplicationAddress; publicIntPtr lpMaximumApplicationAddress; publicUIntPtr 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 voidGetNativeSystemInfo(refSYSTEM_INFOlpSystemInfo); } public static int ProcessorCount { get { NativeMethods.SYSTEM_INFOlpSystemInfo = newNativeMethods.SYSTEM_INFO(); NativeMethods.GetNativeSystemInfo(reflpSystemInfo); return(int)lpSystemInfo.dwNumberOfProcessors; } } } }