Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exceptions from a BackgroundWorker thread?

In a WPF app I have a sheduled database access task, periodically run by a timer and this task have been executed in a BackgroundWorker thread.

When connection attempt failed I raise an exception by try_catch construction and I want to update a Status Bar text in a UI thread.

Is there some prebuild event construction in a BackgroundWorker for implementing this, something like DoWorkEventHandler or RunWorkerCompletedEventHandler, which can be used for this? If not, how to do it better?

Edited (added):

If I want to handle the exception inside RunWorkerCompletedEventHandler, using e.Error parameter, it doesn't work. In case I leave exception unhandled in the BackgroundWorker thread, application hangs on and debugger points to the string of code which is excuted inside BackgroundWorker thread, saying that: Exception was unhandled by user code.

So, in this case, thread doesn't just stop, signalling to RunWorkerCompletedEventHandler that it stopped with error, but the whole application stop working.

like image 594
rem Avatar asked Feb 20 '10 16:02

rem


People also ask

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 use of BackgroundWorker in C#?

As the name suggests the Background Worker Class allows you to set a thread continuously running in the background and communicating with the main thread whenever required. BackgroundWorker makes the implementation of threads in Windows Forms. Intensive tasks need to be done on another thread so the UI does not freeze.


3 Answers

The RunWorkerCompletedEventArgs e of the RunWorkerCompletedEventHandler contains property Error it is of type Exception. If no exception occurred during the work of the background thread the prpery has null as value. Else it contains the error that occurred.

like image 199
IordanTanev Avatar answered Oct 20 '22 21:10

IordanTanev


A WPF UI can be updated from a background thread by using Dispatcher.BeginInvoke.

For example if your background code was part of a Window then you could update a TextBlock:

this.Dispatcher.BeginInvoke((Action)(() =>
    {
        textBlock.Text = "Connection Failed!";
    }));

Edit:

If your background code were in a class other than your Window you could make an interface to help:

public interface IShowStatus
{
    void ShowStatus(string message);
}

Implement the interface in your Window

public void ShowStatus(string message)
{
   this.Dispatcher.BeginInvoke((Action)(() =>
       {
           textBlock.Text = message;
       }));
}

In your class with the background worker make a property to hold a reference to the interface.

public IShowStatus StatusDisplay { get; set; }

In your Window class initialize the background class.

public void InitBackground()
{
    BackgroundClass background = new BackgroundClass();
    background.StatusDisplay = this;
    ...

Finally in your background thread you can say:

StatusDisplay.ShowStatus("Connection Failed!");
like image 36
Doug Ferguson Avatar answered Oct 20 '22 21:10

Doug Ferguson


private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
     Exception exceptionThrowDuringDoWorkEventHandler = e.Error;
}
like image 29
Ken Avatar answered Oct 20 '22 20:10

Ken