title: Why is ThreadStatic data being unexpectedly shared between threads?
body: <p>I have a logging framework that I've written that has the ability to track "logging context". It has a pluggable strategy framework, however the one I use most often is a ThreadStatic variant that keeps track of context in a <code>[ThreadStatic]</code> variable. I've been trying to resolve a problem with logging context in a multi-threaded workflow. The goal is to have all the log entries for all calls across all methods and classes that share a common thread log the same context information. Since each thread should theoretically be getting their own ThreadStatic variable, the idea seemed easy.</p>
  
  <pre><code>public class ThreadStaticLoggingContextStrategy: ILoggingContextStrategy
  {
      public ThreadStaticLoggingContextStrategy()
      {
          Debug.WriteLine("[INITIALIZE] A new instance of 'ThreadStaticLoggingContextStrategy' has been created.");
      }
  
      [ThreadStatic] private LoggingContext _context;
  
      public LoggingContext GetLoggingContext()
      {
          if (_context == null)
              _context = new LoggingContext();
  
          return _context;
      }
  }
  </code></pre>
  
  <p>In reality, it seems that ThreadStatic data is actually being SHARED across threads. This goes against everything I understand about threading. I was having a hard time figuring out what the issue was until I threw in an extra log entry that tracked when each thread cleared out thread context (all the threads run on a main loop...at the beginning, if the necessary messages are received, context is initialized, and at the end in a finally clause, its reset.) The following logging is CONSISTENT:</p>
  
  <blockquote>
    <p>[2011-12-15 16:27:21,233] [DEBUG]
    [TPI.LTI.Eventing.GroupCreatedNotificationHandler:
    TPI.LTI.Provisioning.Handlers.GroupCreatedNotificationHandler.WORKDEVELOPMENT.1_Thread:
    324]: <em>(ContextId=184e82dd-152b-4bb5-a2c6-3e05b2365c04;
    TransactionId=1a11130e-e8dd-4fa1-9107-3b46dcb4ffd6;
    HandlerName=GroupCreatedNotificationHandler;
    HandlerId=WORKDEVELOPMENT.1)</em> Pushing event for tool
    '0967e031-398f-437d-8949-2a17fe844df0' to
    <a href="http://tpidev.pearsoncmg.com/tpi/lti/service/event" rel="noreferrer">http://tpidev.pearsoncmg.com/tpi/lti/service/event</a>...</p>
    
    <p>[2011-12-15 16:27:21,259] [DEBUG] [TPI.LTI.Facades.LTIFacade:
    TPI.LTI.Provisioning.Handlers.GroupCreatedNotificationHandler.WORKDEVELOPMENT.1_Thread:
    299]: <em>(ContextId=184e82dd-152b-4bb5-a2c6-3e05b2365c04;
    TransactionId=1a11130e-e8dd-4fa1-9107-3b46dcb4ffd6;
    HandlerName=GroupCreatedNotificationHandler;
    HandlerId=WORKDEVELOPMENT.1)</em> Getting LTI Tool Instance for tool
    instance guid 0967e031-398f-437d-8949-2a17fe844df0:</p>
    
    <p>[2011-12-15 16:27:21,318] [DEBUG] [TPI.LTI.Facades.LTIFacade:
    TPI.LTI.Provisioning.Handlers.GroupCreatedNotificationHandler.WORKDEVELOPMENT.1_Thread:
    299]: <em>(ContextId=184e82dd-152b-4bb5-a2c6-3e05b2365c04;
    TransactionId=1a11130e-e8dd-4fa1-9107-3b46dcb4ffd6;
    HandlerName=GroupCreatedNotificationHandler;
    HandlerId=WORKDEVELOPMENT.1)</em> Found LTI Tool Instance for tool instance
    guid 0967e031-398f-437d-8949-2a17fe844df0.</p>
    
    <p>[2011-12-15 16:27:21,352] [DEBUG] [TPI.LTI.Facades.TPIFacade:
    TPI.LTI.Provisioning.Handlers.GroupCreatedNotificationHandler.WORKDEVELOPMENT.1_Thread:
    299]: <em>(ContextId=184e82dd-152b-4bb5-a2c6-3e05b2365c04;
    TransactionId=1a11130e-e8dd-4fa1-9107-3b46dcb4ffd6;
    HandlerName=GroupCreatedNotificationHandler;
    HandlerId=WORKDEVELOPMENT.1)</em> Publishing event to TPI at
    'http://tpidev.pearsoncmg.com/tpi/lti/service/event'...</p>
    
    <p>[2011-12-15 16:27:21,428] [DEBUG]
    [TPI.LTI.Eventing.GroupCreatedNotificationHandler:
    TPI.LTI.Provisioning.Handlers.GroupCreatedNotificationHandler.WORKDEVELOPMENT.2_Thread:
    301]:
    <strong>[LOG] Resetting logging Context!!</strong></p>
    
    <p>[2011-12-15 16:27:21,442] [DEBUG]
    [TPI.LTI.Eventing.GroupCreatedNotificationHandler:
    TPI.LTI.Provisioning.Handlers.GroupCreatedNotificationHandler.WORKDEVELOPMENT.2_Thread:
    299]: No message pending on queue.
    GroupCreatedNotificationHandler.WORKDEVELOPMENT.2 handler is
    waiting...</p>
    
    <p>[2011-12-15 16:27:22,282] [DEBUG] [TPI.LTI.Facades.TPIFacade:
    TPI.LTI.Provisioning.Handlers.GroupCreatedNotificationHandler.WORKDEVELOPMENT.1_Thread:
    301]: Event published to TPI.</p>
    
    <p>[2011-12-15 16:27:22,283] [DEBUG]
    [TPI.LTI.Eventing.GroupCreatedNotificationHandler:
    TPI.LTI.Provisioning.Handlers.GroupCreatedNotificationHandler.WORKDEVELOPMENT.1_Thread:
    301]: Received a response from provider:</p>
  </blockquote>
  
  <p>You can see that there are two threads in this particular case, 1_Thread and 2_Thread. I've italicized the contextual data that is supposed to be included at the beginning of EVERY log entry for 1_Thread. I've bolded the point in 2_Thread where logging context is reset. After that point, all of 1_Thread's context information is missing. In dozens of tests so far, the context information for all threads is lost after the logging context is reset on another.</p>
  
  <p>Am I misunderstanding ThreadStatic? I've been writing C# code since 2001, and I've never experienced this behavior before. It seems there is a new <code>ThreadLocal&lt;T&gt;</code> class in .NET 4, however I am not sure if that simply used ThreadStatic internally anyway, and would therefor have the same problem, or if it functions differently (and hopefully more reliably.) Any insight into this problem would be GREATLY APPRECIATED! Thanks!</p>