mike
mike

Reputation: 61

error handling with BackgroundWorker

I know, that you can handle BackgroundWorker errors in RunWorkerCompleted handler, like in next 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 still receive a message : error was unhadled in user code on line

 throw new InvalidOperationException("oh shiznit!"); 

How can i resolve this problem ?

Upvotes: 6

Views: 6116

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

I cannot reproduce the error. The following works fine:

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();
    }
}

Upvotes: 1

as-cii
as-cii

Reputation: 13019

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

Upvotes: 11

Related Questions