title: C# access class members from thread
body: <p>I'm trying to teach myself about threads in C#, and I've run into a problem. Lets say that this is my code:</p>
  
  <pre><code>class MyClass
  {
      public Queue variable;
      internal MyClass()
      {
          variable = new Queue&lt;int&gt;();
          variable.Enqueue(1);
          Thread thread = new Thread(new ThreadStart(DoSomething));
          thread.IsBackground = true;
          thread.Start();
      }
      public void DoSomething()
      {
          int i = variable.Dequeue();
          MessageBox.Show(i);
      }
  }
  </code></pre>
  
  <p>Upon execution I get an exception saying that the queue is empty when I try to dequeue. Debugging shows that the queue is empty within the context of the thread, but not in the larger class. I assume that C# creates thread-local objects for certain things (but not all, if I were to make an int member variable, I could get its value within the thread without any problems) I know java does similiar things, and the way around it is to declare the member variable as "volatile" or something like that. C# has a similiar construct, but I don't think its what I'm looking for (or at least, I used it and it didn't help...) How would I declare a member variable in C# such that any threads created by the class also can access it? (I'd also really like to understand this stuff better, so links to relevant material would be greatly appreciated)</p>