title: C#, Background worker
body: <p>I have a sample WinForms application that uses the <code>BackgroundWorker</code> component. It works fine but when I hit the <code>Cancel</code> button to cancel the background thread it doesn't cancel the thread. When I hit the <code>Cancel</code> button to call <code>.CancelAsync()</code> method, then in <code>RunWorkerCompleted</code> event handler <code>e.Cancelled</code> Property always remains <code>false</code>. I think when I hit <code>Cancel</code> button it should be set to true. </p>
  
  <pre><code>private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
  {
      for (int i = 1; i &lt;= 100; i++)
      {
         // Wait 100 milliseconds.
         Thread.Sleep(100);
         // Report progress.
         if (backgroundWorker1.CancellationPending == true)
         {
             //label1.Text = "Cancelled by user.";
             break;
          }
  
          backgroundWorker1.ReportProgress(i);
       }
  }
  
  private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
  {
      // Change the value of the ProgressBar to the BackgroundWorker progress.
      progressBar1.Value = e.ProgressPercentage;
      // Set the text.
      label1.Text = e.ProgressPercentage.ToString();
  }
  
  private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  {
      if (e.Cancelled == true)
      {
          label1.Text = "Canceled!";
      }
      else if (e.Error != null)
      {
          label1.Text = "Error: " + e.Error.Message;
      }
      else
      {
           label1.Text = "Done!";
      }
  }
  
  private void button2_Click(object sender, EventArgs e)
  {
      if (backgroundWorker1.WorkerSupportsCancellation == true)
      {
          // Cancel the asynchronous operation.
          backgroundWorker1.CancelAsync();
      }
  }
  </code></pre>