Description
This is more of a memo than an "issue," because nothing is broken.
I noticed that we're now wrapping any managed -> native operations that require more than one sequential call with Thread.BeginThreadAffinity and Thread.EndThreadAffinity. At least on the Microsoft CLR, these calls are generally unnecessary.
The idea of making managed threads movable from one OS thread to another I believe dates to the development of CLR 2.0 in the early-mid 2000s. The CLR is itself a COM object that can be hosted inside of existing native applications like SQL Server. The CLR is designed to be able to cooperate with a host's requirements around memory management and threading. One thing that SQL Server was designed to do in the 1990s was to be able to use user-mode threads called "fibers" instead of threads. This yields some non-zero performance advantage by avoiding context switches in the kernel. Some significant work was done to allow the CLR 2.0 to be hosted in SQL Server with fibers mode enabled, but I don't think all the kinks were ever worked out, and to my knowledge we never shipped that feature. (The importance of the fiber mode feature in SQL Server has diminished in the past decade.)
Essentially when you call BeginThreadAffinity/EndThreadAffinity, you are calling through the CLR down into the application which is hosting the CLR, and its implementation of IHostTaskManager::BeginThreadAffinity / EndThreadAffinity. With SQL Server in fiber mode, you definitely lose the permanent association of ManagedThreadId with an OS thread, because a fiber can be scheduled by the user-mode scheduler on any OS thread that is participating in that scheduler. In threads mode, I'm not sure. It may be still necessary, but I doubt it.
The default host that you get when you start a managed application directly in Windows doesn't ever move managed threads from one OS thread to another, so these calls do nothing. Some quick Internet searches seem to indicate that Mono has the same behavior.
The calls to Begin/End are technically correct, but there is probably a performance disadvantage, and no correctness advantage in any mainline scenario.