我正在使用以下代码打开一个在单独线程中的窗口。
它会抛出以下错误:
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
这是什么原因导致的?