Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 调用线程无法访问此对象,因为其他线程拥有它。关闭所有窗口_C#_.net_Wpf_Multithreading - Fatal编程技术网

C# 调用线程无法访问此对象,因为其他线程拥有它。关闭所有窗口

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 =

我正在尝试关闭WPF中的所有窗口。这些窗口都是在不同的线程中生成的

以下是我的功能:

`
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线程上的所有窗口。

哪一行出现错误?