Previously I wrote about how to use core affinity to pin a process to a core on Windows using C/C++. This is just a quick note on how to do so in C#. It’s actually a one liner so much easier than C/C++ unsurprisingly.
System.Diagnostics.Process.GetCurrentProcess().ProcessorAffinity = (System.IntPtr)(1 << coreId);
Above the coreId is a zero indexed number of the core you’d like to pin to. If you pass a coreId that’s incorrect this line of code will fail as below so there’s no need for explicit error checks.
Unhandled Exception: System.ComponentModel.Win32Exception: The parameter is incorrect
In case you’re wondering why anyone would want to limit themselves to one core in a multicore world it’s useful for checking how well single threaded processes perform when running one process per core and how well they scale as the number of processes goes up.
For example you may have 16 cores and because your process is single threaded you may want to run 16 processes each pinned to its respective core. As you deploy more and more processes however you may experience a degradation in how long each takes to perform a set amount of work. This will usually be due to cache overflow and reaching memory bandwidth limitations.