If you have ever bound an ObservableCollection
In WPF, you can use
BindingOperations.EnableCollectionSynchronization
to bind a collection and use it from multiple threads. However, this solution is not very convenient as you need to lock the collection when accessing it and errors are possible.This requires a little more of memory, but this is the trade-off to have an easy to use thread-safe observable collection.
You can safely bind collection.AsObservable to a WPF control. This observable collection implements INotifyCollectionChanged, INotifyPropertyChanged and IReadOnlyList
, so it integrates well with WPF controls.
ThreadSafeObservableCollection is only Available in .NetCore >= 3.0, so you cant use it in Net Framework.
Example:
1 | <ListBox Grid.Row="1" ItemsSource="{Binding Items.AsObservable}" /> |
1 | public ThreadSafeObservableCollection<string> Items { get; } = new ThreadSafeObservableCollection<string>(); |