Popping a MessageBox for the main app with Backgroundworker in WPF Popping a MessageBox for the main app with Backgroundworker in WPF multithreading multithreading

Popping a MessageBox for the main app with Backgroundworker in WPF


It doesn't only not block the main window, it is also very likely to disappear behind it. That's a direct consequence of it running on a different thread. When you don't specify an owner for the message box then it goes looking for one with the GetActiveWindow() API function. It only considers windows that use the same message queue. Which is a thread-specific property. Losing a message box is quite hard to deal with of course.

Similarly, MessageBox only disables windows that belong to the same message queue. And thus won't block windows created by your main thread.

Fix your problem by letting the UI thread display the message box. Use Dispatcher.Invoke or leverage either the ReportProgress or RunWorkerCompleted events. Doesn't sound like the events are appropriate here.


Replace

MessageBox.Show("I should block the main window"); 

with

this.Invoke((Func<DialogResult>)(() => MessageBox.Show("I should block the main window")));

that will cause the message box to be on the main thread and will block all access to the UI until it gets a response. As a added bonus this.Invoke will return a object that can be cast in to the DialogResult.


Call ReportProgress and pass this to MessageBox.Show.