I've got a MVVM setup.
My model periodically calls some service and then invokes an action on the ViewModel which then updates some variables exposed to the View.
The variable is an ReadOnlyObservableCollection<T>
, which has an ObservableCollection<T>
it listens on.
The problem is that the Model calls the callback from a different thread, and thus it doesn't allow me to clear the ObservableCollection<T>
on a different thread.
So I thought: use the dispatcher, if we aren't on the correct thread, invoke it:
private void OnNewItems(IEnumerable<Slot> newItems)
{
if(!Dispatcher.CurrentDispatcher.CheckAccess())
{
Dispatcher.CurrentDispatcher.Invoke(new Action(() => this.OnNewItems(newItems)));
return;
}
this._internalQueue.Clear();
foreach (Slot newItem in newItems)
{
this._internalQueue.Add(newItem);
}
}
Code is pretty straightforward I think.
The problem is that, even though I execute it on the correct thread (I think) it still throws me an exception on the .Clear();
Why is this occuring? How can I work around it without creating my custom ObservableCollection<T>
?