2017-08-16 33 views
0

我曾在一個新的線程創建一個新的窗口,如下:WPF檢查不同UI線程中的窗口可用性?

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實例可用性?

+0

我認爲答案是,「不這樣做」。你爲什麼決定創建一個新線程來打開一個新窗口?如果在該窗口內有一些需要時間的進程,那麼創建一個線程。 – Neil

+0

根據示例代碼,windowNew包含一個快速更新UI的攝像頭視圖。如果我只有在UI線程上,某些操作將被視圖更新阻止。 或者我的案例有其他更好的解決方案嗎? – Paimiya

+0

如果新窗口存在,我不會再創建它。 – Paimiya

回答

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語句和關閉事件處理程序)