调用线程无法访问此对象

调用线程无法访问此对象

本文介绍了调用线程无法访问此对象,因为其他线程拥有它.WPF 关闭所有窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to close all Windows in WPF. The windows were all spawned in different threads.

这是我的功能:

`
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 对象.使用应用程序的调度程序而不是当前窗口的调度程序:

You need to make sure you are accesing the UI objects from the right thread. Use the application's dispatcher instead of the current window's dispatcher:

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);
        }
    }
});

如果您想关闭主窗口,这将起作用,但来自其他线程的窗口不会在集合中.我强烈建议您使用应用程序的调度程序在同一个应用程序 UI 线程上打开所有窗口.

This will work if you want to close the main window, but windows from other threads won't be in the collection. I would strongly suggest you rather use the application's dispatcher to open all windows on the same application UI thread instead.

这篇关于调用线程无法访问此对象,因为其他线程拥有它.WPF 关闭所有窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 08:39