开发者

error handling with BackgroundWorker

开发者 https://www.devze.com 2023-01-21 11:30 出处:网络
I know, that you can handle BackgroundWorker errors in RunWorkerCompleted handler, like in next code

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)
        {
            MessageBo开发者_开发百科x.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 ?


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消