Iniciando uma janela WPF em um segmento separado
Estou usando o código a seguir para abrir uma janela em um thread 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
}
}
Se eu usar esse código em um método, ele funcionará. Mas quando eu o uso da seguinte maneira, recebo um erro:
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
}
}
Emite o seguinte erro:
System.Threading.ThreadStateException
The state of the thread was not valid to execute the operation
Qual é a causa disso?