.NET Backgroundworker - is there no way to resolve exceptions that are usually returned to the main thread?

QUESTION: Reusing .NET Backgroundworker, is there no way that exceptions can usually be returned to the main thread?

PREMISE:

  • Currently, in my WinForms application, I have a generic exception descriptor that goes line by line if (a) a custom application exception that is present to the user but does not exit the program, and (b) if another exception is present and then exit the application
  • The above is great, as I can just throw the appropriate exception anywhere in the application, and the view / processing is handled as a whole
+6
backgroundworker winforms
source share
4 answers

BackgroundWorker will automatically throw an exception. It is located in AsyncCompletedEventArgs.Error when the RunWorkerCompleted event is RunWorkerCompleted .

If you like, you can wrap and rebuild the exception in this event handler, keeping in mind that in the framework, in Invoke.

The exception that occurs in the background thread in a .NET application is a catastrophic error that can and will lead to the destruction of the whole process; the only way to handle this is to wrap all the actions in a try-catch block and save any exception that occurs, which is what BackgroundWorker does.

+6
source share

If the asynchronous method called by DoWork throws an exception, that exception will be 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 occurs during an asynchronous operation, the class will throw an exception for the property error. The client application, the delegate handler, must check the Error property before accessing any properties in the class derived from AsyncCompletedEventArgs; otherwise, the property will raise a TargetInvocationException with its InnerException property containing a link to "Error".

+2
source share

No no.

Instead, you can create a class that inherits BackgroundWorker and overrides OnRunWorkerCompleted to check e.Error and fire an exception handler if it is not null .

+1
source share

Have you tried the static Application.ThreadException event?

0
source share

All Articles