我有一个视图(用户控件),其中包含选项卡控件和选项卡项。当应用程序关闭时,我想删除所有选项卡项,为此,我创建了一个终结器,该终结器调用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));
}
直接调用RemoveAllTabItems函数,而无需使用调度程序。
如上所述,我收到一个错误原因,原因是它来自不同的线程,这就是为什么我试图使用调度程序调用该函数的原因。