title: Backgroundworker : exception during cancellation
body: <p>I have a background worker which can be cancelled.</p>
  <p>The normal flows interrupt itself when the CancelPending variable turns to true (responding to user interaction on UI which call worker.CancelAsynch() ), exceptions are thrown because if that (since normal flow is interrupted, lots of null ref exception are thrown)</p>
  <p>So when the worker returns, I want to be able to distinguish exception that have been thrown when the worker
  was canceled (to silently ignore them) from exceptions thrown when worker was not canceled (to report them to UI).</p>
  <p>My code is as follow (sorry for the c#/vb mix ...) :</p>
  <p>The worker class:</p>
  <pre><code>Public Class ClassBaseGetObjectsWorker
      Inherits System.ComponentModel.BackgroundWorker
      
  
   Protected Overrides Sub OnDoWork(ByVal e As System.ComponentModel.DoWorkEventArgs)
          Try
  
              Dim cpt As Int16 = 0
              While cpt &lt; 5
                  System.Threading.Thread.Sleep(1000)
                  cpt = cpt + 1
                  If CheckForCancellation() Then
                      'Simulating exception due to cancel
                      Throw New Exception(&quot;Exception du to cancel !&quot;)
                  End If
              End While
  
          Catch exc As Exception
              e.Cancel = Me.CancellationPending
              Throw exc
          End Try
  
      End Sub
  End Class
  </code></pre>
  <p>The call back:</p>
  <pre><code>void setObjSetCollWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
      if (e.Cancelled) {
          resultLabel.Text += &quot;Canceled&quot;;
          //e.Error is selently ignored
      }
      else {
          if (e.Error != null) {
              //Reporting errors arising during normal (uncanceled) flow
              throw e.Error.InnerException;
          }
          else {
              //Worker process finished without error or being canceled.
              updateUIAfterBackgroundJob();
          }
      }
  }
  </code></pre>
  <p>Then, when I'm doing worker.CancelAsynch(), e.Cancelled is set to false (which is not what I expected) in the Completed call back. If I comment out &quot;Trow exc&quot; in the worker, if I test again, e.Cancelled is correctly set to true.</p>
  <p>What is the cleanest way to get the information I want, that is: I want to know if the exception popping out in the completed handler was thrown when the worker was in the cancellationPending state or not?</p>