wpf thread-safety observablecollection icollectionview

wpf - Colección observable de ejecución rápida y segura para hilos



thread-safety observablecollection (4)

Aquí hay una compilación de algunas soluciones que hice. La idea de recolección cambió la invocación tomada desde la primera respuesta.

También parece que la operación de "Restablecer" debe ser sincrónica con el hilo principal, de lo contrario, cosas extrañas suceden a CollectionView y CollectionViewSource.

Creo que eso se debe a que en el manejador "Restablecer" se intenta leer los contenidos de la colección de inmediato y ya deberían estar en su lugar. Si hace "Reset" asincrónico y luego agrega de inmediato algunos elementos también asincrónicos, los elementos recién agregados se pueden agregar dos veces.

public interface IObservableList<T> : IList<T>, INotifyCollectionChanged { } public class ObservableList<T> : IObservableList<T> { private IList<T> collection = new List<T>(); public event NotifyCollectionChangedEventHandler CollectionChanged; private ReaderWriterLock sync = new ReaderWriterLock(); protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args) { if (CollectionChanged == null) return; foreach (NotifyCollectionChangedEventHandler handler in CollectionChanged.GetInvocationList()) { // If the subscriber is a DispatcherObject and different thread. var dispatcherObject = handler.Target as DispatcherObject; if (dispatcherObject != null && !dispatcherObject.CheckAccess()) { if ( args.Action == NotifyCollectionChangedAction.Reset ) dispatcherObject.Dispatcher.Invoke (DispatcherPriority.DataBind, handler, this, args); else // Invoke handler in the target dispatcher''s thread... // asynchronously for better responsiveness. dispatcherObject.Dispatcher.BeginInvoke (DispatcherPriority.DataBind, handler, this, args); } else { // Execute handler as is. handler(this, args); } } } public ObservableList() { } public void Add(T item) { sync.AcquireWriterLock(Timeout.Infinite); try { collection.Add(item); OnCollectionChanged( new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, item)); } finally { sync.ReleaseWriterLock(); } } public void Clear() { sync.AcquireWriterLock(Timeout.Infinite); try { collection.Clear(); OnCollectionChanged( new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Reset)); } finally { sync.ReleaseWriterLock(); } } public bool Contains(T item) { sync.AcquireReaderLock(Timeout.Infinite); try { var result = collection.Contains(item); return result; } finally { sync.ReleaseReaderLock(); } } public void CopyTo(T[] array, int arrayIndex) { sync.AcquireWriterLock(Timeout.Infinite); try { collection.CopyTo(array, arrayIndex); } finally { sync.ReleaseWriterLock(); } } public int Count { get { sync.AcquireReaderLock(Timeout.Infinite); try { return collection.Count; } finally { sync.ReleaseReaderLock(); } } } public bool IsReadOnly { get { return collection.IsReadOnly; } } public bool Remove(T item) { sync.AcquireWriterLock(Timeout.Infinite); try { var index = collection.IndexOf(item); if (index == -1) return false; var result = collection.Remove(item); if (result) OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index)); return result; } finally { sync.ReleaseWriterLock(); } } public IEnumerator<T> GetEnumerator() { return collection.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return collection.GetEnumerator(); } public int IndexOf(T item) { sync.AcquireReaderLock(Timeout.Infinite); try { var result = collection.IndexOf(item); return result; } finally { sync.ReleaseReaderLock(); } } public void Insert(int index, T item) { sync.AcquireWriterLock(Timeout.Infinite); try { collection.Insert(index, item); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); } finally { sync.ReleaseWriterLock(); } } public void RemoveAt(int index) { sync.AcquireWriterLock(Timeout.Infinite); try { if (collection.Count == 0 || collection.Count <= index) return; var item = collection[index]; collection.RemoveAt(index); OnCollectionChanged( new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Remove, item, index)); } finally { sync.ReleaseWriterLock(); } } public T this[int index] { get { sync.AcquireReaderLock(Timeout.Infinite); try { var result = collection[index]; return result; } finally { sync.ReleaseReaderLock(); } } set { sync.AcquireWriterLock(Timeout.Infinite); try { if (collection.Count == 0 || collection.Count <= index) return; var item = collection[index]; collection[index] = value; OnCollectionChanged( new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Replace, value, item, index)); } finally { sync.ReleaseWriterLock(); } } } }

ObservableCollection s eleva notificaciones para cada acción realizada en ellos. En primer lugar, no agregan ni quitan llamadas de forma masiva, en segundo lugar no son seguras para subprocesos.

¿Esto no los hace más lentos? ¿No podemos tener una alternativa más rápida? Algunos dicen que ICollectionView envuelto alrededor de un ObservableCollection es rápido? ¿Qué tan cierto es este reclamo?


No puedo agregar comentarios porque todavía no estoy lo suficientemente bueno, pero compartir este problema que encontré probablemente valga la pena publicar aunque no sea realmente una respuesta. Seguí obteniendo una excepción de "Índice estaba fuera de rango" usando esta FastObservableCollection, debido a BeginInvoke. Aparentemente, los cambios que se notifican pueden deshacerse antes de que se llame al controlador, por lo que para solucionar esto pasé lo siguiente como el cuarto parámetro para el BeginInvoke llamado desde el método OnCollectionChanged (en lugar de usar el evento args one):

dispatcherObject.Dispatcher.BeginInvoke (DispatcherPriority.DataBind, handler, this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));

En lugar de esto:

dispatcherObject.Dispatcher.BeginInvoke (DispatcherPriority.DataBind, handler, this, e);

Esto corrigió el problema "El índice estaba fuera de rango" con el que me estaba encontrando. Aquí hay un snpipet de explicación / código más detallado: ¿Dónde obtengo un CollectionView seguro para subprocesos?


Un ejemplo donde se crea una lista Observable sincronizada:

newSeries = new XYChart.Series<>(); ObservableList<XYChart.Data<Number, Number>> listaSerie; listaSerie = FXCollections.synchronizedObservableList(FXCollections.observableList(new ArrayList<XYChart.Data<Number, Number>>())); newSeries.setData(listaSerie);


ObservableCollection puede ser rápido, si lo desea . :-)

El siguiente código es un muy buen ejemplo de una colección observable más segura y rápida, y puede ampliarla más a su gusto.

using System.Collections.Specialized; public class FastObservableCollection<T> : ObservableCollection<T> { private readonly object locker = new object(); /// <summary> /// This private variable holds the flag to /// turn on and off the collection changed notification. /// </summary> private bool suspendCollectionChangeNotification; /// <summary> /// Initializes a new instance of the FastObservableCollection class. /// </summary> public FastObservableCollection() : base() { this.suspendCollectionChangeNotification = false; } /// <summary> /// This event is overriden CollectionChanged event of the observable collection. /// </summary> public override event NotifyCollectionChangedEventHandler CollectionChanged; /// <summary> /// This method adds the given generic list of items /// as a range into current collection by casting them as type T. /// It then notifies once after all items are added. /// </summary> /// <param name="items">The source collection.</param> public void AddItems(IList<T> items) { lock(locker) { this.SuspendCollectionChangeNotification(); foreach (var i in items) { InsertItem(Count, i); } this.NotifyChanges(); } } /// <summary> /// Raises collection change event. /// </summary> public void NotifyChanges() { this.ResumeCollectionChangeNotification(); var arg = new NotifyCollectionChangedEventArgs (NotifyCollectionChangedAction.Reset); this.OnCollectionChanged(arg); } /// <summary> /// This method removes the given generic list of items as a range /// into current collection by casting them as type T. /// It then notifies once after all items are removed. /// </summary> /// <param name="items">The source collection.</param> public void RemoveItems(IList<T> items) { lock(locker) { this.SuspendCollectionChangeNotification(); foreach (var i in items) { Remove(i); } this.NotifyChanges(); } } /// <summary> /// Resumes collection changed notification. /// </summary> public void ResumeCollectionChangeNotification() { this.suspendCollectionChangeNotification = false; } /// <summary> /// Suspends collection changed notification. /// </summary> public void SuspendCollectionChangeNotification() { this.suspendCollectionChangeNotification = true; } /// <summary> /// This collection changed event performs thread safe event raising. /// </summary> /// <param name="e">The event argument.</param> protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { // Recommended is to avoid reentry // in collection changed event while collection // is getting changed on other thread. using (BlockReentrancy()) { if (!this.suspendCollectionChangeNotification) { NotifyCollectionChangedEventHandler eventHandler = this.CollectionChanged; if (eventHandler == null) { return; } // Walk thru invocation list. Delegate[] delegates = eventHandler.GetInvocationList(); foreach (NotifyCollectionChangedEventHandler handler in delegates) { // If the subscriber is a DispatcherObject and different thread. DispatcherObject dispatcherObject = handler.Target as DispatcherObject; if (dispatcherObject != null && !dispatcherObject.CheckAccess()) { // Invoke handler in the target dispatcher''s thread... // asynchronously for better responsiveness. dispatcherObject.Dispatcher.BeginInvoke (DispatcherPriority.DataBind, handler, this, e); } else { // Execute handler as is. handler(this, e); } } } } } }

También ICollectionView que se encuentra sobre la ObservableCollection está activamente al tanto de los cambios y realiza el filtrado, la agrupación y la clasificación relativamente rápido en comparación con cualquier otra lista de fuentes.

De nuevo, las colecciones observables pueden no ser la respuesta perfecta para actualizaciones de datos más rápidas, pero hacen su trabajo bastante bien.