(Posting this with answer because I couldn’t find a full explanation of how to do this anywhere, so I thought it might have some value for someone)
How can I set the processor affinity of a particular thread in Microsoft .Net? Setting the process’s affinity is trivial via System.Diagnostics.Process.ProcessorAffinity, but the System.Threading.Thread class offers no such functionality and .Net doesn’t guarantee a managed thread is linked to any particular operating system thread.
The separation between managed and operating system threads dates back to .Net 2.0, and plans by the SQL Server team to implement .Net threads using fibers. This never really went anywhere, so while there is no guarantee that a managed thread will always run on the same operating system thread, in practice this is always the case for all current .Net hosts. Given that this hasn’t changed in all the years since .Net 2.0’s introduction, it is unlikely this will ever change.
It is possible to strengthen our confidence even for future versions of .Net by using the
System.Threading.Thread.BeginThreadAffinitymethod. This guarantees that the managed thread will stay on the same operating system thread (so it does nothing on the default CLR host, as that is already true by default). I suppose it is still possible that other managed threads can share the same operating system thread, but this seems unlikely and is definitely not the case in any current .Net hosts..Net provides the ability to access native operating system threads using the
System.Diagnostics.ProcessThreadclass, and this class has the ability to change the thread’s processor affinity using theProcessorAffinityproperty. However, linking a particular managed thread to itsProcessThreadwas made deliberately difficult.The only real way to do it is from inside the thread itself. Use the
System.AppDomain.GetCurrentThreadIdmethod (or PInvoke theGetCurrentThreadIdfunction if you don’t want to call a deprecated method, though that would not work with Mono on operating systems other than Windows). This can then be matched to theProcessThread.Idproperty.This makes it possible to set the thread’s processor affinity with the following code (to be called from inside the thread):
Keep in mind that while this works on current versions of .Net, theoretically the lack of a guarantee that managed threads are bound to OS threads could break this code in the future. However, I consider this extremely unlikely.