.NET Framework provides classes which give information about the machine on which code is executed. One Such class is System.Environment which gives us things like Machine Name, OS Version and much more. I recently had a requirement to programmatically detect the number of Processors on a machine. I thought this was a simple enough task. System.Environment.ProcessorCount gives me that information. But I was in for a surprise. Let me walk you through my findings.

On my machine I have a dual core CPU which I can quickly see by opening Task Manager.

Task Manager

What do you think is the output of this statement.

Console.WriteLine(System.Environment.ProcessorCount.ToString());

The output is 2. But I have one physical processor so I expected to see 1. I could not find a way to get this information from the framework. So I went to good old WMI for this. Running this code gives me accurate information about my processor.

ManagementObjectSearcher mgmtObjects = 
  new ManagementObjectSearcher("Select * from Win32_ComputerSystem");

foreach (var item in mgmtObjects.Get())
{
  Console.WriteLine("Number Of Processors - " + 
                     item["NumberOfProcessors"]);
  Console.WriteLine("Number Of Logical Processors - " + 
                     item["NumberOfLogicalProcessors"]);
}

 

And the output this time is

Number Of Processors – 1

Number Of Logical Processors – 2

This is exactly what I need.

So here is my lesson learned. To get detailed and accurate information about number of processors on your machine, WMI is a better approach than System.Environment.ProcessorCount.

kick it on DotNetKicks.com

Tagged with:
 

5 Responses to Get Processor Information In .NET Using C#

  1. Sweet…. This is what I’m looking for

  2. jerodev says:

    This doesn’t work for me.
    I added ‘using System.Management;’
    But i keep getting the following error:
    The type or namespace name ‘ManagementObjectSearcher’ could not be found

  3. Deepak says:

    Jerodev,

    Looks like you are missing a reference to System.Management.dll

  4. SQL tutorial says:

    What is the connection in using C# in a .NET language?

  5. gallyjh says:

    The only thing that stinks about this is that you now require the user to run WMI in services.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>