Unhandled exceptions in BackgroundWorker

Ed Guiness picture Ed Guiness · Nov 3, 2008 · Viewed 25.6k times · Source

My WinForms app uses a number of BackgroundWorker objects to retrieve information from a database. I'm using BackgroundWorker because it allows the UI to remain unblocked during long-running database queries and it simplifies the threading model for me.

I'm getting occasional DatabaseExceptions in some of these background threads, and I have witnessed at least one of these exceptions in a worker thread while debugging. I'm fairly confident these exceptions are timeouts which I suppose its reasonable to expect from time to time.

My question is about what happens when an unhandled exception occurs in one of these background worker threads.

I don't think I can catch an exception in another thread, but can I expect my WorkerCompleted method to be executed? Is there any property or method of the BackgroundWorker I can interrogate for exceptions?

Answer

Ed Guiness picture Ed Guiness · Nov 3, 2008

If the operation raises an exception that your code does not handle, the BackgroundWorker catches the exception and passes it into the RunWorkerCompleted event handler, where it is exposed as the Error property of System.ComponentModel.RunWorkerCompletedEventArgs. 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.

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.dowork.aspx