【发布时间】:2014-04-25 15:24:25
【问题描述】:
我正在使用以下代码在单独的线程中打开一个窗口
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
这是什么原因?
【问题讨论】:
-
你只点击过一次吗? (一个线程不能启动两次)
标签: c# wpf multithreading