Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OKB/HeuristicLab.MainForm.WPF/DispatchedView.cs @ 5155

Last change on this file since 5155 was 4311, checked in by swagner, 14 years ago

Integrated OKB clients for HL 3.3 (#1166)

File size: 2.1 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Collections.ObjectModel;
6using System.Collections.Specialized;
7using System.Threading;
8using System.Collections;
9using System.ComponentModel;
10using System.Windows.Threading;
11
12namespace 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}
Note: See TracBrowser for help on using the repository browser.