如何在一个单独的线程打开一个窗口? [英] How to open a window in a separate thread?

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

问题描述

我想要做的:

Window newWindow = new Window();
newWindow.Show();

while (true) 
{
    Console.Write("spin");
}



也就是说,我做在主窗口的密集计算,但是这个新窗口(在这里我试图以显示与动画繁忙指标)没有响应(这是冷冻)...

I.e., I'm doing an intensive calculation in main window, but this new window (where I'm trying to show a busy indicator with an animation) is not responding (it's frozen)...

于是,我就这样做:

Thread thread = new Thread(() =>
{
    Window newWindow = new Window();
    newWindow.Show();
});

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

while (true) 
{
    Console.Write("spin");
}



但新的窗口仍然冻结,等
有谁知道什么是错在这里?

But the new window is still frozen, etc. Anyone know what's wrong here?

推荐答案

您不要尝试打开它自己的线程的新窗口。

You shouldn't try to open a new Window in it's own thread.

相反,把你正在做的到后台线程的计算工作,并留下UI线程自由。这个最简单的方法通常是使用 BackgroundWorker的。它会自动处理的进度和完成封送处理回UI线程你。

Instead, push the computational work you're doing into a background thread, and leave the UI thread free. The simplest option for this is typically to use BackgroundWorker. It handles the marshaling of progress and completion back to the UI thread for you automatically.

不过,您可以使用线程或工作<做自己/ code> / 任务< T> ,以及。只要记住要将调度程序或从UI方面创造了什么,将更新用户界面,如进度notifcication一个的TaskScheduler。

However, you can do this yourself using threads or Task/Task<T>, as well. Just remember to use the Dispatcher or a TaskScheduler created from the UI context for anything that will update the UI, such as progress notifcication.

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

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