I have a view (user control) that has tab control and tab items in it. When the application closes, i want to remove all tab items and for this i've created a finalizer that calls the RemoveAllTabItems function. However i get an error when trying to access the tab control items: "The calling thread cannot access this object because a different thread owns it." I've tried to fix the error by using the tab control dispatcher but by doing this the remove function is not called.
Sample code for illustration:
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));
}
Call the RemoveAllTabItems function directly, without using dispatcher.