在单独的线程中启动WPF窗口

我正在使用以下代码在单独的线程中打开一个窗口

public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); } private void button1_Click(object sender, RoutedEventArgs e) { Thread newWindowThread = new Thread(new ThreadStart(() => { // Create and show the Window Config tempWindow = new Config(); tempWindow.Show(); // Start the Dispatcher Processing System.Windows.Threading.Dispatcher.Run(); })); // Set the apartment state newWindowThread.SetApartmentState(ApartmentState.STA); // Make the thread a background thread newWindowThread.IsBackground = true; // Start the thread } } 

如果我在方法中使用此代码,它可以工作。 但是当我按如下方式使用它时,我收到一个错误:

 public partial class App : Application { #region Instance Variables private Thread newWindowThread; #endregion protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); newWindowThread = new Thread(new ThreadStart(() => { // Create and show the Window Config tempWindow = new Config(); tempWindow.Show(); // Start the Dispatcher Processing System.Windows.Threading.Dispatcher.Run(); })); } private void button1_Click(object sender, RoutedEventArgs e) { // Set the apartment state newWindowThread.SetApartmentState(ApartmentState.STA); // Make the thread a background thread newWindowThread.IsBackground = true; // Start the thread } } 

它会抛出以下错误:

 System.Threading.ThreadStateException The state of the thread was not valid to execute the operation 

这是什么原因?

@ d.moncada,@ JPVenson,@ TomTom对所有人抱歉,特别是@ d.moncada,你的回答让我意识到我的真​​实错误,确实如果运行一次,直到我的代码工作。 但我真正的问题是我尝试按两个ocation中的button1_Click,真的我采取一个定时器调用一个方法与

  private void button1_Click(object sender, RoutedEventArgs e) 

现在我的问题的解决方案是检测线程已经在C#.net中运行?

我相信问题是你在Thread开始运行后设置了ApartmentState

尝试:

 public partial class App : Application { #region Instance Variables private Thread newWindowThread; #endregion protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); newWindowThread = new Thread(new Thread(() => { // Create and show the Window Config tempWindow = new Config(); tempWindow.Show(); // Start the Dispatcher Processing System.Windows.Threading.Dispatcher.Run(); })); // Set the apartment state newWindowThread.SetApartmentState(ApartmentState.STA); // Make the thread a background thread newWindowThread.IsBackground = true; } private void button1_Click(object sender, RoutedEventArgs e) { // Start the thread newWindowThread.Start(); } } 

你为什么要这样做? (几乎)没有理由在你的应用程序中运行2end UI线程…如果你想要一个非Modal新窗口,请实例化你的窗口并调用show

为何如此? 因为这是一个非常复杂的主题,除非你有一个巨大的变化来完全发展这种行为,你可以没有它。