views:

122

answers:

3

I'm using a background worker in order to get data from a database. My problem is that I'm struggling to report any errors in the database activity.

I've tried straight up spawning a Dialog (Windows Form that I've created) from the DatabaseUpdater class. However, this hangs and I'm left with a white box instead of the error message. I've tried spawning the Dialog in a separate thread - this results in the Dialog appearing and disappearing almost instantly. Obviously I wasn't entirely surprised by this, but attempts at maintaining the Dialog resulted in the same white box effect.

I guess my question is really what is the best practice for displaying errors coming from threaded activity?

+2  A: 

This is a good resource for multithreading and WinForms: Synchronizing calls to the UI in a multi-threaded application

Igor Brejc
I'm so glad that I found your answer here when searching... that is a great article!
Dave
+1  A: 

Assuming the BackgroundWorker task in invoked from the UI thread, you should check for and display any errors in the handler for the RunWorkerCompleted event - do not try to handle them in the DoWork handler method...

Lee
It's a slight workaround - possibly not entirely correct - but what I'm doing is storing the last generated Exception in the DatabaseUpdater class. Once the BackgroundWorker completes I check if the stored Exception is null, if not report the error.Seems to do the job!
Bailz
The RunWorkerCompletedEventArgs passed to the RunWorkerCompleted event contains an Error property which contains any exception.
Lee
A: 

Possibly not what you are looking for, but you might get some mileage out of the InvokeRequired property and Invoke methods on your main form.

JadeMason