Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error handling with BackgroundWorker

Tags:

c#

winforms

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 ?

like image 563
mike Avatar asked Oct 19 '10 08:10

mike


People also ask

What is the difference between BackgroundWorker and thread?

A BackgroundWorker is a ready to use class in WinForms allowing you to execute tasks on background threads which avoids freezing the UI and in addition to this allows you to easily marshal the execution of the success callback on the main thread which gives you the possibility to update the user interface with the ...

What is BackgroundWorker?

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running.

Is BackgroundWorker threaded?

BackgroundWorker, is a component in . NET Framework, that allows executing code as a separate thread and then report progress and completion back to the UI.

What is WPF BackgroundWorker?

BackgroundWorker class is used in scenarios when you have to complete time taking task in the background but make the WPF UI responsive in meantime. BackgroundWorker executes its task in the background thread and update the WPF UI in the UI thread when task is completed.


2 Answers

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.

like image 168
as-cii Avatar answered Sep 19 '22 07:09

as-cii


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();
    }
}
like image 26
Darin Dimitrov Avatar answered Sep 19 '22 07:09

Darin Dimitrov