Error handling with BackgroundWorker

I know that you can handle BackgroundWorker errors in the RunWorkerCompleted handler, as in the following code

var worker = new BackgroundWorker();
worker.DoWork += (sender, e) => 
    { 
        throw new InvalidOperationException("oh shiznit!"); 
    };
worker.RunWorkerCompleted += (sender, e) =>
    {
        if(e.Error != null)
        {
            MessageBox.Show("There was an error! " + e.Error.ToString());
        }
    };
worker.RunWorkerAsync();

But my problem is that I am still receiving the message: the error was not addressable in the user code in the line

 throw new InvalidOperationException("oh shiznit!"); 

How can I solve this problem?

+5
source share
2 answers

You get it because you have a debugger. Try to start the application without a debugger: no exception is thrown, and when the worker completes the operation, you show a MessageBox.

+10
source

I can not reproduce the error. The following works great:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var worker = new BackgroundWorker();
        worker.DoWork += (s, evt) =>
        {
            throw new InvalidOperationException("oops");
        };
        worker.RunWorkerCompleted += (s, evt) =>
        {
            if (evt.Error != null)
            {
                MessageBox.Show(evt.Error.Message);
            }
        };
        worker.RunWorkerAsync();
    }
}
+1
source

All Articles