title: How is BackgroundWorker.CancellationPending thread-safe?
body: <p>The way to cancel a BackgroundWorker's operation is to call <code>BackgroundWorker.CancelAsync()</code>:</p>
  
  <pre><code>// RUNNING IN UI THREAD
  private void cancelButton_Click(object sender, EventArgs e)
  {
      backgroundWorker.CancelAsync();
  }
  </code></pre>
  
  <p>In a BackgroundWorker.DoWork event handler, we check <code>BackgroundWorker.CancellationPending</code>:</p>
  
  <pre><code>// RUNNING IN WORKER THREAD
  void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
  {
      while (!backgroundWorker.CancellationPending) {
          DoSomething();
      }
  }
  </code></pre>
  
  <p>The above idea is all over the web, including on <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker" rel="noreferrer">the MSDN page for BackgroundWorker</a>.</p>
  
  <p>Now, my question is this:  How on earth is this thread-safe?</p>
  
  <p>I've looked at the BackgroundWorker class in ILSpy — <code>CancelAsync()</code> simply sets cancellationPending to true without using a memory barrier, and <code>CancellationPending</code> simply returns cancellationPending without using a memory barrier.</p>
  
  <p>According to <a href="http://www.yoda.arachsys.com/csharp/threads/volatility.shtml" rel="noreferrer">this Jon Skeet page</a>, the above is <em>not</em> thread-safe.  But <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancellationpending.aspx" rel="noreferrer">the documentation for BackgroundWorker.CancellationPending</a> says, "This property is meant for use by the worker thread, which should periodically check CancellationPending and abort the background operation when it is set to true."</p>
  
  <p>What's going on here?  Is it thread-safe or not?</p>