WPF检查不同UI线程中的窗口可用性?

时间:2017-08-16 08:32:49

标签: wpf multithreading

我在新线程中创建了一个新窗口,如下所示:

private WindowNew windowNew;

private void Button_Click(object sender, RoutedEventArgs routedEventArgs)
{
    Thread newWindowThread = new Thread(() =>
    {
        SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher));
        windowNew = new WindowNew();
        windowNew.Show();
        windowNew.Closed += (s, e) => Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
        Dispatcher.Run();
    });
    newWindowThread.SetApartmentState(ApartmentState.STA);
    newWindowThread.IsBackground = true;
    newWindowThread.Start();
}

如何检查windowNew的实例可用性?

1 个答案:

答案 0 :(得分:0)

private void Button_Click(object sender, RoutedEventArgs routedEventArgs)
{
if(windowNew!=null) return;
...
 windowNew.Closed += (s, e) => 
{
Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
windowNew = null;
}
}

您还必须关心同步(if语句和Closed事件处理程序)