STA Thread is not loading the Main Window in WPF

不想你离开。 提交于 2019-12-24 08:51:05

问题


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;

        }

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/15723373/sta-thread-is-not-loading-the-main-window-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!