I'm quite new to threads in c# (WPF) and since I've implemented some label and progressbar update successfully, I do not understand Why when I try to add items to the treeView of my GUI from another class called in a separate thread I get an exception:
An unhandled exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll
Additional information: The calling thread cannot access this object because a different thread owns it.
My update treeview code is this:
private void updateTreeView(TreeView tree, List<TreeViewItem> items, Boolean clear) {
tree.Dispatcher.Invoke(new Action(() => {
if (clear) {
tree.Items.Clear();
}
ItemCollection treeitems = tree.Items;
foreach (TreeViewItem item in items) {
treeitems.Dispatcher.Invoke(new Action(() => {
treeitems.Add(item);
}));
}
tree.ItemsSource = treeitems;
}));
}
And the exception points at the line:
treeitems.Add(item);
Thanks in advance.