tags:

views:

27

answers:

2

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 ?

+2  A: 

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.

AS-CII
yes, this is correct
mike
mark it as the answer then!
Tim
A: 

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