views:

156

answers:

4

Hi,

QUESTION: Re use of .NET Backgroundworker, is there not a way to let exceptions pass back normally to main thread?

BACKGROUND:

  • Currently in my WinForms application I have generic exception handle that goes along the lines of, if (a) a custom app exception then present to user, but don't exit program, and (b) if other exception then present and then exit application
  • The above is nice as I can just throw the appropriate exception anywhere in the application and the presentation/handling is handled generically
+1  A: 

No, there isn't.

Instead, you can make a class that inherits BackgroundWorker and overrides OnRunWorkerCompleted to check e.Error and run exception handler if it's not null.

SLaks
thanks for the idea
Greg
+5  A: 

The BackgroundWorker automatically passes back the exception. It's in the AsyncCompletedEventArgs.Error property when you hook the RunWorkerCompleted event.

If you like, you can wrap and rethrow the exception in this event handler - keeping in mind that there's a bug in the framework that will cause the "outer" exception to be thrown instead because you're in the middle of an Invoke.

An exception that occurs on a background thread in a .NET application is a catastrophic error that can and will bring down the entire process; the only way to deal with this is to wrap all of the activity in a try-catch block and save any exception that occurred, which is exactly what the BackgroundWorker does.

Aaronaught
@Aaronaught - did you mean "that will cause the "inner" exception to be thrown"? (thanks for responding)
Greg
Got it! I just created a new BusinessException inside backgroundWorker1_RunWorkerCompleted and set the innerException to "null".
Greg
+2  A: 

If the asynchronous method called by DoWork throws an exception, that exception will be made available to the RunWorkerCompleted handler. You can handle it there.

private void backgroundWorker1_RunWorkerCompleted(
    object sender, RunWorkerCompletedEventArgs e)
{
    // First, handle the case where an exception was thrown.
    if (e.Error != null)
    {
        MessageBox.Show(e.Error.Message);
    }
    ...
}

From MSDN:

If an exception is raised during an asynchronous operation, the class will assign the exception to the Error property. The client application's event-handler delegate should check the Error property before accessing any properties in a class derived from AsyncCompletedEventArgs; otherwise, the property will raise a TargetInvocationException with its InnerException property holding a reference to Error.

Michael Petrotta
A: 

Have you tried the static Application.ThreadException event?

dkackman