title: Do I need to lock or mark as volatile when accessing a simple boolean flag in C#?
body: <p>Lets just say you have a simple operation that runs on a background thread. You want to provide a way to cancel this operation so you create a boolean flag that you set to true from the click event handler of a cancel button.</p>
  
  <pre><code>private bool _cancelled;
  
  private void CancelButton_Click(Object sender ClickEventArgs e)
  {
      _cancelled = true;
  }
  </code></pre>
  
  <p>Now you're setting the cancel flag from the GUI thread, but you're reading it from the background thread. Do you need to lock before accessing the bool?</p>
  
  <p>Would you need to do this (and obviously lock in the button click event handler too):</p>
  
  <pre><code>while(operationNotComplete)
  {
      // Do complex operation
  
      lock(_lockObject)
      {
          if(_cancelled)
          {
              break;
          }
      }
  }
  </code></pre>
  
  <p>Or is it acceptable to do this (with no lock):</p>
  
  <pre><code>while(!_cancelled &amp; operationNotComplete)
  {
      // Do complex operation
  }
  </code></pre>
  
  <p>Or what about marking the _cancelled variable as volatile. Is that necessary?</p>
  
  <p>[I know there is the BackgroundWorker class with it's inbuilt CancelAsync() method, but I'm interested in the semantics and use of locking and threaded variable access here, not the specific implementation, the code is just an example.]</p>
  
  <p>There seems to be two theories.</p>
  
  <p>1) Because it is a simple inbuilt type (and access to inbuilt types is atomic in .net) and because we are only writing to it in one place and only reading on the background thread there is no need to lock or mark as volatile.<br>
  2) You should mark it as volatile because if you don't the compiler may optimise out the read in the while loop because it thinks nothing it capable of modifying the value.  </p>
  
  <p>Which is the correct technique? (And why?)</p>
  
  <p>[Edit: There seem to be two clearly defined and opposing schools of thought on this. I am looking for a definitive answer on this so please if possible post your reasons and cite your sources along with your answer.]</p>