Wednesday, January 31, 2007

BackgroundWorker and exceptions

Got a bit confused at work today when a piece of software seemingly halted in a place where it should not have been possible.

After looking at the code for a while I found something like the following:

BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork
+= new DoWorkEventHandler(bgw_DoWork);
bgw.RunWorkerAsync();


where bgw_DoWork was (basically) implemented thusly:



void bgw_DoWork(object sender, DoWorkEventArgs e)
{
// ...
throw new Exception("things went bad");
}


If you try it out (outside the debugger) you'll notice that the exception is silently swallowed !?!


The moral of the story:


If you use Background worker, either implement a catch all handler within the DoWork method or, hook the RunWorkerCompleted event and check RunWorkerCompletedEventArgs.Error for non-null value.

No comments: