title: How do I close a WPF application with multiple windows running on separate threads?
body: <p>I am working on a WPF application that I need to completely shut down when the main window is closed. There is another window that can be opened by the program that I open and run like this (variable names are changed, but here is the logic):</p>
  
  <pre><code>private void NewWindowButton_Click(object sender, RoutedEventArgs e) {
      Thread WindowThread = new Thread(new ThreadStart(NewWindowThread));
      WindowThread.SetApartmentState(ApartmentState.STA);
      WindowThread.IsBackground = true;
      WindowThread.Start();
  }
  
  private void NewWindowThread() {
      var NewWindow = new NewWindow();
      NewWindow.Show();
      Dispatcher.Run();
  }
  </code></pre>
  
  <p>When the main window is closed, I have the closing event call the application shutdown method like this:</p>
  
  <pre><code>private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
      Application.Current.Shutdown();
  }
  </code></pre>
  
  <p>This closes all windows that were created within the same thread as the main window, however this is not closing my other windows that I opened with in new threads. How do I make sure that all of my windows close when the main window closes?</p>
  
  <p>Edit: The linked post only partially answered my question. Using the function <code>Environment.Exit(0);</code> worked for closing every window, but it is causing all of my windows to close about 2-3 seconds after clicking the X button, whereas <code>Application.Current.Shutdown();</code> closes the windows immediately but leaves the other threads open. There is nothing happening on the same thread after Shutdown gets called so I do not need a return statement after it.</p>