views:

301

answers:

3

I've been struggling with event handling in backgroundworker threads.

All the documentation I've come across make me believe that when a DoWork event handler throws an exception that exception should be dealt with in the RunWorkerCompleted handler and that exception will be available in the Error property of the RunWorkerCompletedEventArgs.

This is fine, but during debug time I always see an exception unhandled by user code message. This makes me believe there is a problem with my approach.

What steps should I take to resolve this?

Regards, Jonathan

A: 

Your approach is correct. Just press continue on the message and keep going. If in doubt, test it outside of a debug session.

Ray
A: 

I've had this problem before. The e.Error only gets set when you don't run in Debug mode. If you run in Debug, exectuion stops at the spot of the Exception. However, run the same program in Non debug mode (in VS Debug -> Start Without Debugging or Ctrl+F5) and the nasty exception dialog WON'T come up, and e.Error will be the exception. Not sure why, but that's how it works....

BFree
A: 

I've seen this behavior before, and I've gotten around it by decorating the DoWork handler with the System.Diagnostics.DebuggerNonUserCode attribute:

[System.Diagnostics.DebuggerNonUserCode]
void bw_DoWork(object sender, DoWorkEventArgs e)
{ ... }

Note that you'll only see this if you're running in the debugger; even without the attribute, all is as it should be when running from the shell.

I looked this up again, and I still can't see any good reason why you need to do this. I'm calling it a debugger misfeature.

Michael Petrotta
Why you need to do this? Because it's how BackgroundWorker works. A lot easier to handle the error in the calling thread than in the working thread. But when debugging, the other way is true since you get access to all local variables.
Samuel
I don't think "it's how BackgroundWorker works" is a satisfying answer. It sounds like you see all exceptions as indicative of coding errors - that's true only sometimes. If I wanted the debugger to break on a handled exception, I'd turn on first-chance exceptions or set a breakpoint.
Michael Petrotta