如何在单独的线程上创建和显示WPF窗口? [英] How do I create and show WPF windows on separate threads?

查看:321
本文介绍了如何在单独的线程上创建和显示WPF窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从同一过程中创建两个(或更多)WPF窗口.但是窗口必须由单独的线程处理,因为它们不应相互阻塞.我该怎么做?

I need to create two (or more) WPF windows from the same process. But the windows must be handled by separate threads because they should not be able to block each other. How do I do this?

在WinForms中,这是通过以下方式实现的:

In WinForms this is achieved by:

  • 开始一个新线程
  • 从新线程创建表单
  • 调用Application.Run以表单作为参数

但是我如何在WPF中做同样的事情?

But how do I do the same in WPF?

推荐答案

msdn 状态:

private void NewWindowHandler(object sender, RoutedEventArgs e)
{       
    Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
    newWindowThread.SetApartmentState(ApartmentState.STA);
    newWindowThread.IsBackground = true;
    newWindowThread.Start();
}

private void ThreadStartingPoint()
{
    Window1 tempWindow = new Window1();
    tempWindow.Show();       
    System.Windows.Threading.Dispatcher.Run();
}

这是一个旧的答案,但是由于它似乎经常被访问,因此我还可以想到以下修改/改进(未经测试).

this IS an old answer, but since it seems to be visited often, I could also think of the following modifications/improvements (not tested).

如果您想关闭这样的窗口,只需从线程外部(委托)保留对Window对象的引用,然后在其上调用close,如下所示:

If you would like to close such a window, simply keep a reference to the Window object from outside of the thread (delegate), and then invoke close on it, something like this:

void CloseWindowSafe(Window w)
{
    if (w.Dispatcher.CheckAccess())
        w.Close();
    else
        w.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(w.Close));
}

// ...
CloseWindowSafe(tempWindow);

如果新线程可能被终止(强制中止),则符合注释中的问题:

If the new thread could become terminated (aborted forcibly), in line with question in comments:

private void ThreadStartingPoint()
{
    try{
        Window1 tempWindow = new Window1();
        tempWindow.Show();       
        System.Windows.Threading.Dispatcher.Run();
    }
    catch(ThreadAbortException)
    {
        tempWindow.Close();
        System.Windows.Threading.Dispatcher.InvokeShutdown();
    }
    //the CLR will "rethrow" thread abort exception automatically
}

免责声明:不要在家中这样做,中止线程(几乎总是)是违反最佳实践的.应该通过各种同步技术中的任何一种来优雅地处理线程,或者在这种情况下,只需通过调用的window.Close()

DISCLAIMER: don't do this at home, aborting threads is (almost always) against best practices. Threads should be gracefully handled via any of the various synchronization techniques, or in this case, simply via an invoked window.Close()

这篇关于如何在单独的线程上创建和显示WPF窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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