Regs Regs - 1 year ago 84
C# Question

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

I want to handle exceptions that happen inside of

handler in my
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

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download