I would like some explanation on how C# (WPF) works behind the code. Situation (clearly hypothetical for the sake of simplicity):
On our UI thread, we create the Settings object. It has a variable:
public ObservableCollection<Something> collection;
From a different background thread, we call
try{
Settings.Modify()
}
which then does the following:
Settings.Modify()
{
collection = new ObservableCollection<Something>();
collection.Add(...)
}
Now, of course this throws an exception at the Add function:
This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.
But the collection = new ObservableCollection(); line executed. As far as I know, this new collection was created on the stack of the background thread. The WPF UI binds to this variable:
<ItemsControl ItemsSource="{Binding Settings.collection}"
In my understanding, the UI thread should not be able to access this collection anymore. What would happen if it tried, could it block the UI thread for some reason?
Oher question: Why did the compiler let me replace an object which clearly belongs on the UI thread with an other on the background thread, even though it knows I'm messing up when I tried to Add to that collection from another thread.
EDIT:
This problem's solution is already answered here
:
What I am still curious about this: If the
collection = new ObservableCollection<Something>();
function is called alone, what would the UI thread do if it tried to access this collection?