Search code examples
c#.netmultithreadingaffinitycpu-cores

Is Core Affinity Something that We Can Safely Do in .NET?


I have looked here in StackOverflow for information implementing Core Affinity for a Thread,
in .NET.

Some answers say that .NET does not support it for its own (managed) threads,
and only supports it for the non-managed threads running on the operating system.

On the other hand, other answers, mention the following properties:
- ProcessThread.IdealProcessor link
- ProcessThread.ProcessorAffinity link

As can be seen, those 2 properties are not properties of the Thread class, but of the ProcessThread class.

So I would like to ask:
If someone is creating a .NET application,
and wants to set the Core affinity for the Threads of his application,
is it safe and supported to do that, on the .NET Managed Threads?

(If yes, then I wonder why those 2 properties are exposed on the ProcessThread class
and not on the Thread class?)

PS: I am using .NET Framework v3.5 and v2.0,
and not the newer versions of the Framework.


Solution

  • No.

    .NET threads do not map 1:1 to operating system threads. Thread affinity is for operating system threads. Since the runtime can switch .NET threads between OS threads at will, setting processor affinity will do nothing at best, and waste performance in a typical multi-threaded scenario.

    Note that ProcessThread simply contains information about running operating system thread in a process. It's just what you get when you ask what threads a process has - it's part of the OS, not .NET. In contrast, Thread is about your threads, and only the managed ones.