I'm using the following code for to open a window in a separate thread
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
}
}
If I use this code in a method, it works. But when I use it as follows, I get an 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
}
}
It throws the following error:
System.Threading.ThreadStateException
The state of the thread was not valid to execute the operation
What is the cause of this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…