1

I have a windows from application with a program.cs code like this:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.ThreadException += (sndr, evnt) => 
        { 
            MessageBox.Show("An error occur. Please contact your administrator.\nError description: " + 
                evnt.Exception.Message + "\nStack trace:\n" + evnt.Exception.StackTrace, 
                evnt.Exception.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error); 
        };
        Application.Run(new frmLogin());
    }
}

But when an exception is thrown inside the BackgroundWorker.DoWork event, the Application.ThreadException didn't catch it.

How can the Application.ThreadException catch an exception from a different thread created by a BackgroundWorker?

I know catching errors in the Application.ThreadException is not a good practice but we only use it as our last level of error catching.

My code is in C#, framework 4, build in VS2010 Pro.

Please help. Thanks in advance.

1

2 Answers 2

4

See this question: BackgroundWorker exceptions don't get propagated like that, so you can't catch them in ThreadException.

BackgroundWorkers that throw exceptions call RunWorkerCompleted as usual, but set the Error property on the event arguments.

1

The BackgroundWorker catches exception for you(will not expose to Application.ThreadException or AppDomain.UnhandledException) and pass the exception to argument of RunWorkerCompleted event. You will handle the exception on RunWorkerCompleted event handler.

There is RunWorkerCompletedEventArgs.Error that you can get the exception once the RunWorkerCompleted event fired.

    private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null)
        { 
            // handle exception here
        }
    }
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.