[4311] | 1 | using System;
|
---|
| 2 | using System.Collections.Generic;
|
---|
| 3 | using System.Linq;
|
---|
| 4 | using System.Text;
|
---|
| 5 | using System.Collections.ObjectModel;
|
---|
| 6 | using System.Collections.Specialized;
|
---|
| 7 | using System.Threading;
|
---|
| 8 | using System.Collections;
|
---|
| 9 | using System.ComponentModel;
|
---|
| 10 | using System.Windows.Threading;
|
---|
| 11 |
|
---|
| 12 | namespace HeuristicLab.BackgroundProcessing {
|
---|
| 13 | /// <summary>
|
---|
| 14 | /// Takes an <code>ObservableEnumerable</code> and transfers all events to the
|
---|
| 15 | /// specified Dispatcher. It also keeps a cache of the collection to ensure
|
---|
| 16 | /// the Dispatcher sees a consistent state.
|
---|
| 17 | /// </summary>
|
---|
| 18 | /// <typeparam name="T"></typeparam>
|
---|
| 19 | public class DispatchedView<T> : IObservableEnumerable<T> {
|
---|
| 20 | private List<T> cache;
|
---|
| 21 | private IObservableEnumerable<T> source;
|
---|
| 22 | private Dispatcher Dispatcher;
|
---|
| 23 | private DispatcherPriority Priority;
|
---|
| 24 |
|
---|
| 25 | public event NotifyCollectionChangedEventHandler CollectionChanged;
|
---|
| 26 |
|
---|
| 27 | public DispatchedView(IObservableEnumerable<T> source, Dispatcher dispatcher, DispatcherPriority priority) {
|
---|
| 28 | cache = source.ToList();
|
---|
| 29 | source.CollectionChanged += source_CollectionChanged;
|
---|
| 30 | this.source = source;
|
---|
| 31 | Dispatcher = dispatcher;
|
---|
| 32 | Priority = priority;
|
---|
| 33 | }
|
---|
| 34 |
|
---|
| 35 | void source_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
|
---|
| 36 | Dispatcher.BeginInvoke(new Action(() => {
|
---|
| 37 | if (e.Action == NotifyCollectionChangedAction.Add) {
|
---|
| 38 | cache.InsertRange(e.NewStartingIndex, e.NewItems.Cast<T>());
|
---|
| 39 | } else if (e.Action == NotifyCollectionChangedAction.Remove) {
|
---|
| 40 | cache.RemoveRange(e.OldStartingIndex, e.OldItems.Count);
|
---|
| 41 | } else {
|
---|
| 42 | cache = source.ToList();
|
---|
| 43 | }
|
---|
| 44 | OnCollectionChanged(e);
|
---|
| 45 | }), Priority, null);
|
---|
| 46 | }
|
---|
| 47 |
|
---|
| 48 | protected void OnCollectionChanged(NotifyCollectionChangedEventArgs args) {
|
---|
| 49 | if (CollectionChanged != null)
|
---|
| 50 | CollectionChanged(this, args);
|
---|
| 51 | }
|
---|
| 52 |
|
---|
| 53 | public IEnumerator<T> GetEnumerator() {
|
---|
| 54 | return cache.GetEnumerator();
|
---|
| 55 | }
|
---|
| 56 |
|
---|
| 57 | IEnumerator IEnumerable.GetEnumerator() {
|
---|
| 58 | return GetEnumerator();
|
---|
| 59 | }
|
---|
| 60 | }
|
---|
| 61 | }
|
---|