BindingOperations.EnableCollectionSynchronization mystery in WPF

I am trying to understand this concept, and even after many experiments, I still can’t understand that it is best to use ObservableCollections in WPF and use BindingOperations.EnableCollectionSynchronization.

If I have a viewmodel with an observable collection, and I enable collection synchronization using locking, as shown below:

m_obsverableCollection = new ObservableCollection<..>; BindingOperations.EnableCollectionSynchronization(m_obsverableCollection, m_obsverableCollectionLock); 

Does this mean that every modification and listing for this observable collection will:

  • Block collection automatically with m_obsverableCollectionLock?
  • Marshall all the changes in the thread on which the collection was created?
  • Marshall all the changes in the thread on which the bind operation call was made?

When using BindingOperations.EnableCollectionSynchronization, will I ever need to do any locking explicitly?

The problem that caused all this is that even after using BindingOperations.EnableCollectionSynchronization and locking the elements using the same lock, I passed this method, very often I get "This type of CollectionView does not support changes to the SourceCollection from a stream other than Dispatcher thread. " An exception

+7
c # wpf
source share
2 answers

Finally we got to the end:

We must enable CollectionSynchronization in the dispatcher:

 Application.Current.Dispatcher.BeginInvoke(new Action(()=> { BindingOperations.EnableCollectionSynchronization(m_obsverableCollection, m_observableCollectionLock); })); 

Then, every time any other thread wants to access the observable, you can simply:

 lock (m_observableCollectionLock) m_observableCollection.Add(...) 
+6
source share

I have not used this specific syntax, but whenever I need to update an ObservableCollection from a background thread, I follow this pattern:

 // i just typed this off the top of my head, so be forewarned... :) lock(someLockingObj) { Application.Current.Dispatcher.BeginInvoke(new Action(()=> { ... update here.... })); } 

Usually the error you encounter occurs when the bg thread tries to update the ObservableCollection directly, without Dispatcher.BeginInvoke (or even Invoke will work too, most of the time, IMHO).

+2
source share

All Articles