Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.BackgroundProcessing/3.2/DispatchedView.cs @ 2404

Last change on this file since 2404 was 2404, checked in by epitzer, 15 years ago

Move BackgroundProcessing Project into version subfolder. (#769)

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
14  /// <summary>
15  /// Takes an <code>ObservableEnumerable</code> and transfers all events to the
16  /// specified Dispatcher. It also keeps a cache of the collection to ensure
17  /// the Dispatcher sees a consistent state.
18  /// </summary>
19  /// <typeparam name="T"></typeparam>
20  public class DispatchedView<T> : ObservableEnumerable<T> where T : class {
21
22    private List<T> cache;
23    private ObservableEnumerable<T> source;
24    private Dispatcher Dispatcher;
25    private DispatcherPriority Priority;
26
27    public event NotifyCollectionChangedEventHandler CollectionChanged;
28
29    public DispatchedView(ObservableEnumerable<T> source, Dispatcher dispatcher, DispatcherPriority priority) {
30      cache = source.ToList();
31      source.CollectionChanged += source_CollectionChanged;
32      this.source = source;
33      Dispatcher = dispatcher;
34      Priority = priority;
35    }
36
37    void source_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
38      Dispatcher.BeginInvoke(new Action(() => {
39        if (e.Action == NotifyCollectionChangedAction.Add) {
40          cache.InsertRange(e.NewStartingIndex, e.NewItems.Cast<T>());
41        } else if (e.Action == NotifyCollectionChangedAction.Remove) {
42          cache.RemoveRange(e.OldStartingIndex, e.OldItems.Count);
43        } else {
44          cache = source.ToList();
45        }
46        OnCollectionChanged(e);
47      }), Priority, null);
48    }
49
50    protected void OnCollectionChanged(NotifyCollectionChangedEventArgs args) {
51      if (CollectionChanged != null)
52        CollectionChanged(this, args);
53    }   
54
55    public IEnumerator<T> GetEnumerator() {
56      return cache.GetEnumerator();
57    }
58
59    IEnumerator IEnumerable.GetEnumerator() {
60      return GetEnumerator();
61    }
62  }
63}
Note: See TracBrowser for help on using the repository browser.