I have an MVVM setup.
My model periodically calls some service, and then calls an action in the ViewModel, which then updates some of the variables that are displayed in the view.
The variable is ReadOnlyObservableCollection<T>
, which has an ObservableCollection<T>
that is listening.
The problem is that the model is calling a callback from another thread and thus does not allow me to clear the ObservableCollection<T>
from another thread.
So, I thought: use the dispatcher, if we are not in the right thread, call 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); } }
The code is pretty simple, I think.
The problem is that although I am executing it in the correct thread (I think), it still throws me an exception on .Clear();
Why is this happening? How can I get around this without creating a custom ObservableCollection<T>
?
Snake source share