C# - Number Of Cores and Processors

27. October 2011 13:55

 

If your working with threads in c# is can be useful to be able to find out the number of processors and the total number of cores avilable to an application so that you can adjust the maximum number of threads to a sensible value when an application starts. After all there is no point in attempting to execute 100 high processor intensive task's in a system with only 2 cores. It will just grind your application and possibly windows to a complete halt.

 

Heres is some code to find that information out

 

public static class ThreadSystemInfo
{
	private static bool HasData = false;

	private static void Init()
	{
		if (HasData)
			return;

		ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_Processor");
		ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql);
		ManagementObjectCollection results = searcher.Get();

		foreach(ManagementObject result in results) {
			_NumberOfCores = int.Parse(result["NumberOfCores"].ToString());
			_NumberOfLogicalProcessors = int.Parse(result["NumberOfLogicalProcessors"].ToString());
			break;
		}

		HasData = true;
	}

	private static int _NumberOfCores = 0;
	public static int NumberOfCores
	{
		get
		{
			Init();
			return _NumberOfCores;
		}
	}

	private static int _NumberOfLogicalProcessors = 0;
	public static int NumberOfLogicalProcessors
	{
		get
		{
			Init();
			return _NumberOfLogicalProcessors;
		}
	}
}

E-mail Kick it! DZone it! del.icio.us Permalink


Comments (3) -

10/30/2011 6:30:41 PM #

FYI, just checking the number of processors may be wrong as your application may be given a custom processor affinity. Also, you may have 2 logical processors, but only 1 actual processor.
Depending of what you want to achieve this is important to take into account.

Héctor Spain |

2/9/2012 8:06:09 AM #

Hi,

Can you show me the full code ?
I copy this code to my C# environment , and can't recognize 'ObjectQuery' and some instruments. Do I need include some header references ?
Please kindly reply me via email , thank you very much.

Qizhong Yang People's Republic of China |

2/9/2012 6:48:03 PM #


you SystemManagment added to the project then several namespaces includes. You can find these using the object browsers in visual studio

james United Kingdom |

Pingbacks and trackbacks (1)+