Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does System.Windows.MessageBox lag a WPF window?

Consider the following code:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    MessageBox.Show("MyMessage");
}

If I am trying to display a message box after a WPF window has been loaded, when I run the application, the WPF window is displayed with a transparent background (only the non-client area is visible) and it takes 3-5 seconds until the message box appears. The WPF window returns to normal only after the message box has been closed.

Is this normal? Does anyone else experience this?

EDIT: I have added a screenshot of how the window looks like:

enter image description here

like image 601
IneedHelp Avatar asked Nov 30 '25 09:11

IneedHelp


1 Answers

The MessageBox is getting shown at the Normal DispatcherPriority, which occurs before things like DataBind, Render, and Loaded, so the code that initializes your Window's objects is not getting run until after you dismiss the MessageBox

You can fix this by simply showing the MessageBox at a later DispatcherPriority, such as Background

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    InitializeComponent();

    this.Dispatcher.BeginInvoke(DispatcherPriority.Background, 
        new Action(delegate() { MessageBox.Show("MyMessage"); }));
}
like image 180
Rachel Avatar answered Dec 02 '25 22:12

Rachel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!