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;
}
}
}
5c46ddb4-1588-47f0-b60d-80825cdb608b|1|4.0