Synchronization mechanism for an observable object

前端 未结 3 2292
情深已故
情深已故 2021-02-18 16:59

Let\'s imagine we have to synchronize read/write access to shared resources. Multiple threads will access that resource both in read and writing (most of times for reading, some

3条回答
  •  爱一瞬间的悲伤
    2021-02-18 17:49

    Cross-Thread Collection Synchronization

    Putting a ListBox binding to a ObservableCollection , when the data changes , you update the ListBox because INotifyCollectionChanged implemented . The defect dell'ObservableCollection is that the data can be changed only by the thread that created it.

    The SynchronizedCollection does not have the problem of Multi-Thread but does not update the ListBox because it is not implemented INotifyCollectionChanged , even if you implement INotifyCollectionChanged , CollectionChanged (this, e) can only be called from the thread that created it .. so it does not work.

    Conclusion

    -If you want a list that is autoupdated mono-thread use ObservableCollection

    -If you want a list that is not autoupdated but multi-threaded use SynchronizedCollection

    -If you want both, use Framework 4.5, BindingOperations.EnableCollectionSynchronization and ObservableCollection () in this way :

    / / Creates the lock object somewhere
    private static object _lock = new object () ;
    ...
    / / Enable the cross acces to this collection elsewhere
    BindingOperations.EnableCollectionSynchronization ( _persons , _lock )
    

    The Complete Sample http://10rem.net/blog/2012/01/20/wpf-45-cross-thread-collection-synchronization-redux

提交回复
热议问题