How to catch Exception in Background Worker

Juval Lowy provides the BackgroundWorker component to facilitate easy asynchronous invocation with Windows Forms in Net 1.1, but when an exception occurs in BackgroundWorker(DoWork event) – it behaves as though happened nothing.It is possible to understand what happened just by analyzing Error
argument as shown below:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
 throw new ApplicationException("exception");
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
 string message = string.Empty;
 if( e.Cancelled )
 {
   message = "Cancelled";
 }
 else
 {
  if(e.Error !=null)
  { // analyze error here
    message = "Error";
  }
  else
  {
    message = "Stoped";
  }
 }
 
 MessageBox.Show(message);
}


 
 
 

Leave a Reply