MessageBox.Show()导致WPF应用程序运行?

时间:2016-06-17 15:03:06

标签: c# wpf

在我的WPF应用程序的App.xaml.cs内,从入口点Main()开始,它看起来像这样:

[STAThread]
public static void Main()
{
    var app = new App();
    app.StartApp();
}

当取消注释两个MessageBox中的任何一个时,我会遇到一些意外行为。

protected void StartApp()
{
    // uncomment this  = the messagebox will show and return after 'okay' is clicked.
    // The application will never start even after `this.Run()` is called?
    //MessageBox.Show("Hello");
    this.InitializeComponent(); //auto generated code
    this.StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
    // uncomment this = the messagebox will show and simultaneously the application will run().
    // The line below will only be hit on termination of the application
    //MessageBox.Show("Hello");
    this.Run();
}

猜测一下,MessageBox.Show正在使用当前的应用程序上下文做一些时髦的事情,因为MessageBox.Show的第一行Main()完全符合预期。

2 个答案:

答案 0 :(得分:0)

除了WPF特定内容之外,

Application.Run()调用Dispatcher.Run()。 最后一个运行窗口消息循环。 MessageBox.Show内的原生消息框也是如此。

因此应避免在Application.Run()之前调用消息框。

答案 1 :(得分:0)

Task.Run(()=>MessageBox.Show("Hello")).Wait()将产生预期的'结果 - 即它的消息泵不会影响调用应用程序的执行。

相关问题