How do you detect the number of physical processors/cores in .net?
While Environment.ProcessorCount will indeed get you the number of virtual processors in the system, that may not be the number of processors available to your process. I whipped up a quick little static class/property to get exactly that:
using System;
using System.Diagnostics;
///
/// Provides a single property which gets the number of processor threads
/// available to the currently executing process.
///
internal static class ProcessInfo
{
///
/// Gets the number of processors.
///
/// The number of processors.
internal static uint NumberOfProcessorThreads
{
get
{
uint processAffinityMask;
using (var currentProcess = Process.GetCurrentProcess())
{
processAffinityMask = (uint)currentProcess.ProcessorAffinity;
}
const uint BitsPerByte = 8;
var loop = BitsPerByte * sizeof(uint);
uint result = 0;
while (--loop > 0)
{
result += processAffinityMask & 1;
processAffinityMask >>= 1;
}
return (result == 0) ? 1 : result;
}
}
}