How to handle exceptions from a BackgroundWorker thread? How to handle exceptions from a BackgroundWorker thread? wpf wpf

How to handle exceptions from a BackgroundWorker thread?


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.


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!");


private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e){     Exception exceptionThrowDuringDoWorkEventHandler = e.Error;}