Getting the total number of processors a computer has (c#)

Posted by mbcrump on Geeks with Blogs See other posts from Geeks with Blogs or by mbcrump
Published on Sun, 04 Apr 2010 13:11:41 GMT Indexed on 2010/04/04 20:23 UTC
Read the original article Hit count: 218

Filed under:

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

    }
}

© Geeks with Blogs or respective owner