.NET Threads, CallContext and ILogicalThreadAffinative
I've recently been looking for a way to automatically pass information from a thread's current call context to any thread that's been spawned from this thread. This can be useful for many reasons, and sometimes having some TLS information like the current user, or some custom context information.
This can be done by wrapping any thread entry point around some custom code that will effectively pass the context to the new thread. This is a bit annoying, especially if this is information that is generated internally by a framework, because it requires the user of the framework to always use the wrapping method.
There's a way around this by using the CallContext class, and particularly GetData/SetData methods. Problem is, if you set some data in the CallContext, it will not pass onto a spawned thread. Actually, it will if the type you are placing in the CallContext implements the ILogicalThreadAffinative interface.
This is a marker interface that is used to avoid context data that is not meant to "flow" through each spawned thread.
It's also interesting to know that ILogicalThreadAffinative flagged types will also be passed along to threads spawned by the thread pool, and incidentally to delegates enqueued via the BeginInvoke compiler generated method.
Finally, in case of a remoting call, any ILogicalThreadAffinative flagged type will also serialized to the remote context and be serialized back to the local context.
Being able to step through the Framework's code has been somehow a time saver to better understand this :)