STA Thread未加载WPF中的主窗口

时间:2013-03-30 20:53:48

标签: c# .net wpf multithreading sta

我在App_Startup()中加载MainWindow。我想在加载窗口时显示进度条。但它不起作用:

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();

}

我想从线程加载窗口:

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

            _loadingProgressBar.ShouldCloseNow = true;

        }

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

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;
}

你基本上从线程中想要显示窗口时将它发送到主应用程序线程。因此,当线程从主线程显示MainWindow时退出时,这会停止应用程序关闭。

答案 1 :(得分:0)

我怀疑窗口缺少消息泵,因为WPF Application类及其Dispatcher在不同的STA线程上运行