Exceptions in BackgroundWorker

By admin - Last updated: Thursday, December 17, 2009 - Save & Share - Leave a Comment

To save 15 minutes of confusion.

If an exception is thrown in a BackgroundWorker’s DoWork handler, the backgroundworker will catch it and place the exception in RunWorkerCompleted’s e.Error.

If it seems like the Exception’s still being thrown with no apparent way to catch it, it’s becauseĀ if e.Error is not null. When that’s the case, e.Result will throw that error (wrapped in a TargetInvocationException) when accessed. Do not access e.Result without checking for e.Error first.

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  EndCreate(e.Error, e.Result); // <--- THIS WILL CRASH IF e.Error IS NOT NULL
}
 
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  // THIS WILL NOT.
  if (e.Error == null) {
    EndCreate(e.Error, e.Result);
  }
  else {
    EndCreate(e.Error, null); // accessing e.Result throws the exception
  }
}
Posted in .NET, C# • • Top Of Page

Write a comment

Currently you have JavaScript disabled. In order to post comments, please make sure JavaScript and Cookies are enabled, and reload the page. Click here for instructions on how to enable JavaScript in your browser.