当我关闭启动画面时 WPF 应用程序关闭

WPF application closes when I close Splash Screen

我想在新线程中向我的 WPF 应用程序添加启动画面(因为加载 Main window 的数据时我的动画启动画面挂起)。代码:

SplashScreenWindow splashScreenWindow = null;
Thread newWindowThread = new Thread(() =>
{
    splashScreenWindow = new SplashScreenWindow();
    splashScreenWindow.ShowDialog();
});
newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.IsBackground = true;
newWindowThread.Start();

   data loading...

_mainWindow.Show();
splashScreenWindow.Close();

我的问题是当我关闭初始屏幕时程序关闭。

因为 .Show() 不是阻塞调用,这意味着它会 return 不管 window 实际关闭,所以应用程序将 运行 结束超过可能。

使用.ShowDialog()

确保在调用此之前关闭初始屏幕。

我做过类似的事情,这对我有用。

SplashScreenWindow splashScreenWindow = null;
Thread newWindowThread = new Thread(() =>
{
    splashScreenWindow = new SplashScreenWindow();
    splashScreenWindow.Show();
    System.Windows.Threading.Dispatcher.Run();
});
newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.IsBackground = true;
newWindowThread.Start();

data loading...

_mainWindow.Show();

您过早调用关闭,从主 window 加载事件调用 splashScreenWindow.Close()。

_mainWindow.Loaded += (s,ev) => { 
splashScreenWindow.Dispatcher.Invoke(new Action(.splashScreenWindow.Close));
};