我正在使用以下代码在单独的线程中打开窗口

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

这是什么原因造成的?

最佳答案

@ d.moncada,@ JPVenson,@ TomTom对所有人表示抱歉,尤其是@ d.moncada,您的回答使我意识到了我的真正错误,实际上,如果在我的代码运行之前运行一次。但是我真正的问题是我尝试在两个位置按下button1_Click,实际上我使用了一个计时器,该计时器使用

 private void button1_Click(object sender, RoutedEventArgs e)

现在我的问题的解决方案是Detecting a Thread is already running in C# .net?

10-07 15:49