【问题标题】:The calling thread cannot access this object because a different thread owns it. WPF closing all windows调用线程无法访问此对象,因为不同的线程拥有它。 WPF关闭所有窗口
【发布时间】:2014-06-05 02:58:30
【问题描述】:

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

这是我的功能:

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

}`

【问题讨论】:

  • 哪一行出现错误?

标签: c# .net wpf multithreading


【解决方案1】:

您需要确保从正确的线程访问 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);
        }
    }
});

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多