(I use .Net 4.5, with Visual Studio 2017. Minimal example link has been added at the end of the post, and is ready to run/crash without anything to do if you want to see the things by yourselves)
I have a UserControl that contains a DataGrid in WPF. It's bound to a Viewmodel that contains a DataTable, AND a custom list of columns, in order to hide some of them when I can't delete them right at the moment for example.
DataGrid.Columns is readonly, so in the UserControl.DataContextChanged (I explain below why), I get the new DataContext, clear my grid.Columns collection and feed it with the custom list of DataGridColums I've read at load time.
Initially, I was doing a sync load. Everything was running fine (I'm loading many things, including a list of these Items). But I've put the loading into a backgroundworker (which ran almost fine) and, later, replaced the backgroundworker by an async loading using Task.Run().
All of the other lists of item in my window are well loaded, the code runs fine. BUT the moment I'm trying to replace mygrid.Columns by other ones, I have a InvalidOperationException saying that the calling thread can't access this object because another thread owns it.
I've tried many things, many BeginInvoke from myGrid.Dispatcher, App's current Dispatcher and so on, and every piece of async code I found, but I cannot figure out how to add a simple item to this ObservableCollection.
I've seen custom asyncObservableCollection but can't use them, DataGrid.Columns being read-only.
I'm puzzled by the fact that I thought UserControl_DataContextChanged was belonging to the UI thread, so it should be able to change user controls safely.
I've updloaded a "minimal example" here => https://files.fm/u/k2srba6m The problem is in ItemViewmodel.FilterColumns, as my original code does (hope the solution to this will work on the original code too)
Any help would be appreciated (and sorry for my english)