Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background Worker Event Handling

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

like image 935
jon37 Avatar asked Oct 26 '22 06:10

jon37


2 Answers

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.

like image 101
Michael Petrotta Avatar answered Nov 11 '22 16:11

Michael Petrotta


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....

like image 30
BFree Avatar answered Nov 11 '22 16:11

BFree