title: Setting a global variable in a thread - C#
body: <p>I have an HTTP server that I am writing using HTTP listener, and I would like to somehow declare certain variables as accessible from anywhere within a thread. </p>
  
  <ul>
  <li>My webserver class is instanced based, so I can't really use a static variable.</li>
  <li>I could use an instance variable as all of the code is in one class, but...I don't know.</li>
  </ul>
  
  <p>I thought of using a dictionary: <code>Dictionary&lt;/*[type of Thread ID here]*/,ThreadData&gt;</code>, but I'm concerned there might be threading issues. <code>ThreadData</code> would <em>probably</em> be a class instance, but I might use a struct, depending on which would be more efficient.</p>
  
  <ul>
  <li>If I would key the dictionary to the Thread IDs and program it so that one thread would <em>only</em> ask for its own entry in the dictionary, would there be any thread-related problems when accessing the dictionary?</li>
  <li>Each thread would add its own entry. Would I have to lock the dictionary while I add new thread items? If so, would I be able to use a separate lock object to allow threads to access their own data in the meantime? </li>
  </ul>
  
  <p>Would there be an advantage to using a concurrent dictionary? Is there another way that is more thread-safe?</p>
  
  <p>I am currently using <code>ThreadPool.QueueUserWorkItem</code>. I don't know for sure that this uses a new thread for each item. If not then I could also key it to the context. </p>
  
  <p><strong>Update:</strong> According to <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool%28v=vs.100%29.aspx">ThreadPool class - MSDN</a>, it does reuse threads. And it does not clear thread data.</p>
  
  <blockquote>
    <p>When the thread pool reuses a thread, it does not clear the data in thread local storage or in fields that are marked with the ThreadStaticAttribute attribute. Therefore, when a method examines thread local storage or fields that are marked with the ThreadStaticAttribute attribute, the values it finds might be left over from an earlier use of the thread pool thread.</p>
  </blockquote>