Last active
August 29, 2015 13:59
-
-
Save JohanLarsson/10497547 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class History<T> : IEnumerable<HistoryItem<T>>, INotifyCollectionChanged | |
| { | |
| private readonly ConcurrentStack<HistoryItem<T>> _stack = new ConcurrentStack<HistoryItem<T>>(); | |
| public void Push(T item) | |
| { | |
| _stack.Push(new HistoryItem<T>(item)); | |
| OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item)); | |
| } | |
| public IEnumerator<HistoryItem<T>> GetEnumerator() | |
| { | |
| return _stack.GetEnumerator(); | |
| } | |
| IEnumerator IEnumerable.GetEnumerator() | |
| { | |
| return GetEnumerator(); | |
| } | |
| public event NotifyCollectionChangedEventHandler CollectionChanged; | |
| protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) | |
| { | |
| NotifyCollectionChangedEventHandler handler = CollectionChanged; | |
| if (handler != null) | |
| { | |
| if (Application.Current != null && Application.Current.Dispatcher != null) | |
| { | |
| Application.Current.Dispatcher.BeginInvoke(new Action(() => handler(this, e))); | |
| } | |
| else | |
| { | |
| handler(this, e); | |
| } | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class HistoryItem<T> | |
| { | |
| public HistoryItem(T value) | |
| { | |
| Timestamp = DateTime.UtcNow; | |
| Value = value; | |
| } | |
| public DateTime Timestamp { get; private set; } | |
| public T Value { get; private set; } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class ObservingHistory<T> : History<T>, IDisposable | |
| { | |
| private IDisposable _subscription; | |
| public ObservingHistory(IObservable<T> observable) | |
| { | |
| _subscription = observable.Subscribe(Push); | |
| } | |
| public void Dispose() | |
| { | |
| Dispose(true); | |
| GC.SuppressFinalize(this); | |
| } | |
| protected virtual void Dispose(bool disposing) | |
| { | |
| if (disposing) | |
| { | |
| if (_subscription != null) | |
| { | |
| _subscription.Dispose(); | |
| _subscription = null; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment