C# 调用线程无法访问此对象,因为其他线程拥有它。关闭所有窗口
我正在尝试关闭WPF中的所有窗口。这些窗口都是在不同的线程中生成的 以下是我的功能:C# 调用线程无法访问此对象,因为其他线程拥有它。关闭所有窗口,c#,.net,wpf,multithreading,C#,.net,Wpf,Multithreading,我正在尝试关闭WPF中的所有窗口。这些窗口都是在不同的线程中生成的 以下是我的功能: ` private void Button_Click(object sender, RoutedEventArgs e) { this.Dispatcher.Invoke(() => { foreach (Window window in Application.Current.Windows) { if (window =
`
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Dispatcher.Invoke(() =>
{
foreach (Window window in Application.Current.Windows)
{
if (window == Application.Current.MainWindow)
window.Close();
}
//MessageBox.Show(varWindows.ToString());
//for (int intCounter = App.Current.Windows.Count; intCounter > 0; intCounter--)
// App.Current.Windows[intCounter - 1].Hide();
});
}`
您需要确保您正在从正确的线程访问UI对象。使用应用程序的调度程序而不是当前窗口的调度程序:
Application.Current.Dispatcher.Invoke(() =>
{
var a = Application.Current.Windows.Count;
foreach (Window window in Application.Current.Windows)
{
if (window == Application.Current.MainWindow)
{
var windowHandle = window;
window.Dispatcher.Invoke(windowHandle.Close);
}
}
});
如果要关闭主窗口,这将起作用,但来自其他线程的窗口将不在集合中。我强烈建议您使用应用程序的dispatcher来打开同一应用程序UI线程上的所有窗口。哪一行出现错误?