Regs Regs - 8 days ago 6
C# Question

How to handle exception that has been thrown from DoWork handler of BackgroundWorker?

I want to handle exceptions that happen inside of

DoWork
handler in my
RunWorkerCompleted
handler but while code is running under debugger I'm getting another exception first "Exeption was unhandled by user code".

Here short example of code I'm using:

BackgroundWorker _worker;
public void Test()
{
_worker = new BackgroundWorker();
_worker.WorkerReportsProgress = false;
_worker.WorkerSupportsCancellation = false;

_worker.DoWork += new DoWorkEventHandler(bw_DoWork);
_worker.RunWorkerCompleted += new
RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
_worker.RunWorkerAsync();
}

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = ActuallWorkHere();
}

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

private IEnumerable<string> ActuallWorkHere()
{
throw new Exception("test");
// "Exeption was unhandled by user code" if called
string[] res = { "test" };
return res;
}


What am I doing wrong?

Answer

You're not really doing anything wrong, this is what Visual Studio does with unhandled errors when running code in the debugger:

From BackgroundWorker.DoWork Event on MSDN:

If you are running under the Visual Studio debugger, the debugger will break at the point in the DoWork event handler where the unhandled exception was raised.

Try running your compiled program and you won't see this.

Note that you can handle this exception in your DoWork and the RunWorkerCompletedEventArgs.Error property in your RunWorkerCompleted handler will still store details of your error.

Comments