title: Making variables captured by a closure volatile
body: <p>How do variables captured by a closure interact with different threads? In the following example code I would want to declare totalEvents as volatile, but C# does not allow this.</p>
  
  <p>(Yes I know this is bad code, it's just an example)</p>
  
  <pre><code>private void WaitFor10Events()
  {
       volatile int totalEvents = 0; // error CS0106:
  
       _someEventGenerator.SomeEvent += (s, e) =&gt; totalEvents++;
  
       while(totalEvents &lt; 10)
          Thread.Sleep(100);
  }
  </code></pre>
  
  <p><strong>EDIT</strong>: People seem to be missing the point of my question a bit. I know I can't use <code>volatile</code> on local vars. I also know that the example code code is bad and could be implemented in other ways, hence my "bad code" disclaimer. It was just to illustrate the problem.</p>
  
  <p>Anyway, it would appear that there is no way to force volatile semantics onto captured local variables, so I will implement a different way. Thanks for the answers though, I have learned a couple of useful things anyway. :)</p>