My BackgroundWorker
's RunWorkerCompletedEventHandler
invokes a function in my main thread, which shows a MessageBox
dialog. I tested what happens if I invoke the BW periodically (with a Timer
) and I don't understand why this causes me to get multiple message boxes over time. I mean, shouldn't the GUI thread be blocked during the call to my RunWorkerCompletedEventHandler
function?
Whenever I close a dialog, the rest of the function gets executed as normal, for every dialog box.
If I replace the MessageBox.Show
with a Thread.Sleep
, then I don't have this problem. The function calls all get executed one after the other. No second invocation happens during the sleep, like it does with the MessageBox
-es.
Why is this unexpected behavior happening for a MessageBox
and can I change it to block the thread properly?
Displaying a message box (or closing one) is not an activity that requires continuous use of the UI thread. The UI thread is used to create new UI that represents the message box but it then goes back into (a version of) the message loop wherein it waits for new work to do.
This is why e.g. the message box can be responsive, be moved around the screen, etc, because the UI thread is free to react to the required events.