'Why Showing a dialog in App() constructor prevents WPF app showing up?
I used visual studio to create a new wpf application. I added a constructor for the app:
using System.Windows;
namespace WpfApplication
{
public partial class App : Application
{
App() : base()
{
MessageBox.Show("foo", "bar");
}
}
}
The application will only show the message box, then it will not show the main window after you close the message box.
However, if I make it a static constructor like:
using System.Windows;
namespace WpfApplication
{
public partial class App : Application
{
static App()
{
MessageBox.Show("foo", "bar");
}
}
}
It will be able to launch the main window.
Can someone help me in understanding what's wrong with the first method?
Solution 1:[1]
Because StartupUrl is not set yet.
In the constructor of System.Windows.Application, it invoke an async operation. And what we care about is DoStartup method in that async operation, in which it checks if StartupUrl is null.
When invoke an async operation, it post a message and that should be handled after you call App.Run().
Calling MessageBox.Show needs to use the current dispatcher, then the previous inovked operation will be handled(but StartupUrl is not set).
For the static constructor, it is called before constructor, so no such problem exist.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mingpepe |
