Lanzar una ventana WPF en un hilo separado
Estoy usando el siguiente código para abrir una ventana en un hilo separado
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
}
}
Si uso este código en un método, funciona. Pero cuando lo uso de la siguiente manera, me sale un error:
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
}
}
Lanza el siguiente error:
System.Threading.ThreadStateException
The state of the thread was not valid to execute the operation
¿Cuál es la causa de esto?