C# thread safety (in particular MVVM/WPF)
c#, mvvm, wpf
Solution
My app has a background thread that periodically updates the value of Total. Assuming nothing else updates Total, what (if anything) should I do to make all this thread-safe?
For scalar properties, you don't need to do anything special; the `PropertyChanged` event is automatically marshaled to the UI thread.
Now, what if I wanted to do something similar but using a property of type Dictionary<>, or ObservableCollection<>? Which members (add, remove, clear, indexer) are thread-safe? Should I use a ConcurrentDictionary instead?
No, this is not thread-safe. If you change the content of an `ObservableCollection<T>` from a background thread, it will break. You need to do it on the UI thread. An easy way to do it is to use a collection that raises its events on the UI thread, like the one described here.
As for `Dictionary<TKey, TValue>`, it doesn't raise a notification when its content changes, so the UI is not notified anyway.
Problem
I'm wondering what I need to do to make models thread safe in MVVM. Say I had the following class, which is instantiated as a singleton: ``` public class RunningTotal: INotifyPropertyChange { private int _total; public int Total { get { return _total; } set { _total = value; PropertyChanged("Total"); } } ...etc... } ``` My view model exposes it via a property: ``` public RunningTotal RunningTotal { get; } ``` And my view has a textblock bound to it, i.e. `{Binding Path=RunningTotal.Total}`. My app has a background thread that periodically updates the value of Total. Assuming nothing else updates Total, what (if anything) should I do to make all this thread-safe? Now, what if I wanted to do something similar but using a property of type `Dictionary<>`, or `ObservableCollection<>`? Which members (add, remove, clear, indexer) are thread-safe? Should I use a ConcurrentDictionary instead?