Warm tip: This article is reproduced from stackoverflow.com, please click
wpf dispatcher finalizer

WPF

发布于 2020-03-27 15:44:26

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));
}
Questioner
sysboard
Viewed
65
Naresh Goradara 2012-03-02 19:43

Call the RemoveAllTabItems function directly, without using dispatcher.