title: Can a C# thread really cache a value and ignore changes to that value on other threads?
body: <p>This question is <em>NOT</em> about race-conditions, atomicity, or why you should use locks in your code. I already know about those.</p>
  
  <p>UPDATE: My question isn't "does weirdness with volatile memory exist" (i know it does), my question is "doesn't the .NET runtime abstract that away so you'll never see it". </p>
  
  <p>See <a href="http://www.yoda.arachsys.com/csharp/threads/volatility.shtml" rel="nofollow noreferrer">http://www.yoda.arachsys.com/csharp/threads/volatility.shtml</a>
  and the first answer on <a href="https://stackoverflow.com/questions/434890/is-a-string-property-itself-threadsafe">Is a string property itself threadsafe?</a></p>
  
  <p>(They're really the same article since one references the other.) One thread sets a bool and the other thread loops forever reading that bool -- those articles claim the reading thread might cache the old value and never read the new value, so therefore you need a lock (or use the volatile keyword). They claim the following code will potentially loop forever.
    Now I agree it's good practice to lock your variables, but I can't believe the .NET runtime would really ignore a memory value changing as the article claims. I understand their talk about volatile memory vs non-volatile memory, and I agree they have a valid point in <em>non-managed</em> code, but I can't believe the .NET runtime won't correctly abstract that away so that the following code does what you expect. 
    The article even admits the code will "almost certainly" work (though not guaranteed), so I'm calling BS on the claim. Can anyone verify that it's true the following code won't always work? Is anyone able to get even one case (maybe you can't always reproduce it) where this fails? </p>
  
  <pre><code>class BackgroundTaskDemo
  {
      private bool stopping = false;
  
      static void Main()
      {
          BackgroundTaskDemo demo = new BackgroundTaskDemo();
          new Thread(demo.DoWork).Start();
          Thread.Sleep(5000);
          demo.stopping = true;
      }
  
      static void DoWork()
      {
           while (!stopping)
           {
                 // Do something here
           }
      }
  }
  </code></pre>