WPF-终结和UI线程

问题描述 投票:0回答:2

我有一个视图(用户控件),其中包含标签控件和标签项目。当应用程序关闭时,我想删除所有选项卡项,为此,我创建了一个终结器,该终结器调用RemoveAllTabItems函数。但是,尝试访问选项卡控件项时出现错误:“调用线程无法访问该对象,因为其他线程拥有它。”我试图通过使用选项卡控件调度程序来修复错误,但是这样做不会调用remove函数。

示例代码:

private void RemoveAllTabItems()
{
    IEnumerable<TabItem> tabs = this.myTabControl.GetTabItems();
    foreach (TabItem tab in tabs)
            TryClose(tab);
}

~MyClass()
{
    this.myTabControl.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(RemoveAllTabItems));
    // Already tried these:
    // this.myTabControl.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(RemoveAllTabItems));
    // this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(RemoveAllTabItems));
}
wpf dispatcher finalizer
2个回答
0
投票

不使用分派器直接调用RemoveAllTabItems函数。


0
投票

Application.Current.Dispatcher.BeginInvoke可能值得一试,因为它应确保它在UI线程上执行。如果您是通过VS运行此程序,则可能值得在清理功能的开始处放置一个断点,并检查线程窗口以查看点击该线程时所处的线程。

© www.soinside.com 2019 - 2024. All rights reserved.