Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Why is my background worker thread signaling done when it isn't?

C#, using VS2010 and I've got something that makes no sense.

At startup my program needs to load several hundred k from text files. After ensuring the loading code was working fine I threw it in a background thread. So long as this is run from within the IDE everything's fine but when it's run standalone the thread says it's done when it isn't. This of course goes boom.

The trigger code:

BackgroundWorker Background = new BackgroundWorker();
Background.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DatabaseLoaded);
Background.DoWork += new DoWorkEventHandler(delegate { Database.Load(); });
Background.RunWorkerAsync();

and the stuff that's going boom is in DatabaseLoaded().

I put some messageboxes to trace what's going on: The first and last lines of the Load() method and the first line of DatabaseLoaded().

In the IDE this triggers as I expect: Load() beginning, Load() done, DatabaseLoaded(). However, when run standalone I get Load() beginning, DatabaseLoaded() and then the unhandled exception box (the loader hasn't even gotten to build empty tables, let alone fill them.)

Am I nuts or is Microsoft?

like image 340
Loren Pechtel Avatar asked Dec 20 '10 22:12

Loren Pechtel


2 Answers

RunWorkerCompleted will be invoked in case of an error (such as an unhandled exception in Database.Load()). Check the Error property of the RunWorkerCompletedEventArgs.

like image 171
Sam B Avatar answered Oct 30 '22 13:10

Sam B


There's probably an exception thrown from Database.Load(). BackgroundWorker catches any unhandled exception before triggering the RunWorkerCompleted event. Check the RunWorkerCompletedEventArgs.Error property in DatabaseLoaded.

like image 36
Ondrej Tucny Avatar answered Oct 30 '22 11:10

Ondrej Tucny