1

When I show a message box from within an async method, the z-Order of the new message box may be wrong, and the box might be missed by the user.

Consider the following code:

private async void btnShowMessage_Click(object sender, EventArgs e)
{
    await Task.Delay(3000);
    MessageBox.Show("Test");
}

Run this application, click the ShowMessage-Button and activate some different window. When the message is shown, it can appear in the background. Since it correctly blocks interaction with the main window, to the user it seems that the application is hanging.

I know, that this can be prevented by explicitly supplying an owner to the Show()-method. Anyways, I was wondering whether there is a more generic solution to this problem (actually, I was expecting the ExecutionContext to handle this).

hofingerandi
  • 517
  • 4
  • 20

1 Answers1

1

According to the source code of MessageBox.Show. https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/MessageBox.cs,451867ccabfb0df5

When owner is not assigned, it will get the active window using unsafe methods (so the active window, after 3000 ms of wait, may be your application, other applications or the even the desktop). So it is better to assign the owner.

If async methods are not called in a synchronize way, code in async method will not be run on UI Thread. Access to UI elements (DependencyObject, not in your case) are now allowed, you should use the Dispatcher too.

You can find your answer here:

Force MessageBox to be on top of application window in .net/WPF

h.yuan
  • 138
  • 10
  • 5
    "running methods in async method means the code is not running on UI Thread". That's not really true. If your code is *called* on the UI thread and no `await`s use `ConfigureAwait(false);`, one of the *jobs* of the async state machine is to make sure you *do* end up running back on the UI thread. – Damien_The_Unbeliever Sep 12 '18 at 11:47
  • Thanks for your explication about ConfigureAwait(false), i think some async pattern for my application can be simplified by this :) – h.yuan Sep 12 '18 at 12:07
  • The OP already knows about owner: "I know, that this can be prevented by explicitly supplying an owner to the Show()-method" – Poul Bak Sep 12 '18 at 12:11
  • Thank you for the link. Looking at referencesource, it seems clear that there is no other solution than explicitly setting the owner. Thank you. – hofingerandi Sep 13 '18 at 12:30