I have been writing up some instrumentation documentation where I have been explaining the use of TraceFilter implementations. I gave an example of creating a TraceFilter that filters trace events from the TraceListener based on the identity of the executing thread. The issue here is that a TraceListener implementation may be writing its data on a different thread to the one that invoked the trace event. I had always assumed that when you create a new thread, the identity of the creating thread is used as the identity of the new thread. There is a lot of danger in assumptions though. While it’s just an example, I needed to prove that my TraceFilter code wouldn’t be invalid if a TraceListener did use threads for its work.
After firing up Reflector, I poked around Thread.CurrentPrincipal code. As expected, the principal is stored in the context data of the thread (LogicalCallContext via CallContext). What was interesting about the code is that if the call context doesn’t contain a principal, it then consults the AppDomain. In the internal AppDomain.GetThreadPrincipal() method, the code runs a switch around a PrincipalPolicy value. I hadn’t come across PrincipalPolicy before so this was an interesting discovery.