在一个单独的线程启动一个WPF窗口 [英] Launching a WPF Window in a Separate Thread

查看:1000
本文介绍了在一个单独的线程启动一个WPF窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用在一个单独的线程

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

是什么原因呢?

推荐答案

@ d.moncada,@JPVenson,@TomTom对不起大家,espetially为@ d.moncada,你的回答让我意识到我真正的错误,事实上,如果直到我的代码工作运行一次。但我真的问题是,我试图推动的button1_Click两个ocation,我真的需要一个计时器,称为以

@d.moncada, @JPVenson, @TomTom sorry for everyone, espetially to @d.moncada, your answer made me realize my true error, indeed if run once until my code works. But my really problem is that i try to push button1_Click in two ocation, really i take a timer that called a method with the line of the

 private void button1_Click(object sender, RoutedEventArgs e)

现在我的问题的解决方案是< A HREF =http://stackoverflow.com/questions/12949024/detecting-a-thread-is-already-running-in-c-sharp-net>检测线程是用C#.net已经运行?

Now the solution of my problem is Detecting a Thread is already running in C# .net?

这篇关于在一个单独的线程启动一个WPF窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆