STA Thread is not loading the Main Window in WPF

2019-08-02 05:27发布

I am loading MainWindow in App_Startup (). I wanted to show the progress bar while loading the window. But it is not working :

void App_Startup(object sender, StartupEventArgs e)
{

    Thread bootStrapThread = new Thread(new ThreadStart(runBootStrapProcess));
    bootStrapThread.SetApartmentState(ApartmentState.STA);
    bootStrapThread.IsBackground = true;
    bootStrapThread.Start();
    _loadingProgressBar = new loadingProgressBar();
    _loadingProgressBar.ShowDialog();

}

I want to load the window from thread :

void runBootStrapProcess()
        {
            MetadataReader mr = new MetadataReader();  
            if (currentVersionNo.Equals(remoteVersionNo))
            {
                Application.Current.Shutdown();
            }
            else
            {
                MainWindow mw = new MainWindow();
                mw.Show();
            }

            _loadingProgressBar.ShouldCloseNow = true;

        }

2条回答
Viruses.
2楼-- · 2019-08-02 06:13

I suspect the window is missing the message pump since the WPF Application class with its Dispatcher is running on a different STA Thread

查看更多
smile是对你的礼貌
3楼-- · 2019-08-02 06:17

You can try this:

void runBootStrapProcess() {
  MetadataReader mr = new MetadataReader();
  if (currentVersionNo.Equals(remoteVersionNo)) {
    Application.Current.Shutdown();
  } else {
    System.Windows.Application.Current.Dispatcher.BeginInvoke(
    new Action(
      () => {
        MainWindow mw = new MainWindow();
        mw.Show();
      }));
  }
  _loadingProgressBar.ShouldCloseNow = true;
}

You basically from the thread when you want to show the window send it to the main application thread. This thus stops the application from closing down when the thread exits since the MainWindow is Shown from the main thread.

查看更多
登录 后发表回答