为什么 System.Windows.MessageBox 会导致 WPF 窗口卡顿?

3
请参考以下代码:

考虑以下代码:

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

如果我在WPF窗口加载后尝试显示一个消息框,运行应用程序时,WPF窗口会显示为透明背景(只有非客户端区域可见),并且需要3-5秒钟才能出现消息框。只有在关闭消息框后,WPF窗口才会恢复正常。
这是正常现象吗?还有其他人经历过这种情况吗?
编辑:我已添加了一个窗口外观的截图:

你使用的是哪个 MessageBox? - Bob.
@Bob。根据问题标题,应使用System.Windows.MessageBox。实际上,有人发布了一个(现已删除的)答案,以确保您使用的是System.Windows而不是System.Windows.Forms,因为System.Windows.Forms会拉取几个WPF通常不需要的dll,而OP已经确认他们正在使用System.Windows.MessageBox - Rachel
2个回答

7
MessageBox会在Normal DispatcherPriority中显示,此时先于诸如DataBindRenderLoaded等操作,因此直到你关闭MessageBox后才会执行初始化窗口对象的代码。
你只需在稍后的DispatcherPriority中(例如Background)显示MessageBox即可解决这个问题。
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    InitializeComponent();

    this.Dispatcher.BeginInvoke(DispatcherPriority.Background, 
        new Action(delegate() { MessageBox.Show("MyMessage"); }));
}

0
尝试使用Show方法的this重载,或者接受Window实例作为参数的任何其他重载。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接