How do I update an ObservableCollection via a worker thread?

前端 未结 4 658
忘了有多久
忘了有多久 2020-11-22 05:23
4条回答
  •  长情又很酷
    2020-11-22 05:57

    Collection synchronization code for posterity. This uses simple lock mechanism to enable collection sync. Notice that you'll have to enable collection sync on the UI thread.

    public class MainVm
    {
        private ObservableCollection _collectionOfObjects;
        private readonly object _collectionOfObjectsSync = new object();
    
        public MainVm()
        {
    
            _collectionOfObjects = new ObservableCollection();
            // Collection Sync should be enabled from the UI thread. Rest of the collection access can be done on any thread
            Application.Current.Dispatcher.BeginInvoke(new Action(() => 
            { BindingOperations.EnableCollectionSynchronization(_collectionOfObjects, _collectionOfObjectsSync); }));
        }
    
        /// 
        /// A different thread can access the collection through this method
        /// 
        /// The new mini vm to add to observable collection
        private void AddMiniVm(MiniVm newMiniVm)
        {
            lock (_collectionOfObjectsSync)
            {
                _collectionOfObjects.Insert(0, newMiniVm);
            }
        }
    }
    

提交回复
热议问题