DelayedPresentRollingObservableCollection.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Collections.Specialized;
  5. using System.ComponentModel;
  6. using System.Diagnostics;
  7. using System.Runtime.CompilerServices;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using System.Windows;
  11. using System.Windows.Threading;
  12. namespace MECF.Framework.UI.Client.ClientBase.Collections
  13. {
  14. /// <summary>
  15. /// The collection is thread-safe.
  16. /// </summary>
  17. /// <typeparam name="T"></typeparam>
  18. public class DelayedPresentRollingObservableCollection<T> : IEnumerable<T>, INotifyCollectionChanged, INotifyPropertyChanged
  19. {
  20. #region Variables
  21. public event NotifyCollectionChangedEventHandler CollectionChanged;
  22. private readonly List<T> _list;
  23. private readonly List<T> _cache;
  24. private readonly object _lockList;
  25. private readonly object _lockCache;
  26. private readonly SemaphoreSlim _semListEnumLocker;
  27. private readonly int _presentDelayMillisec = 200; // the default delay is 200ms
  28. #endregion
  29. #region Constructors
  30. public DelayedPresentRollingObservableCollection(int capacity)
  31. {
  32. if (capacity <= 0)
  33. throw new ArgumentException("the capacity must be grate than 0.", nameof(capacity));
  34. _lockList = new object();
  35. _lockCache = new object();
  36. _semListEnumLocker = new SemaphoreSlim(0, 1);
  37. Capacity = capacity;
  38. lock (_lockList)
  39. {
  40. _list = new List<T>();
  41. }
  42. lock (_lockCache)
  43. {
  44. _cache = new List<T>();
  45. }
  46. _semListEnumLocker.Release();
  47. _ = Task.Run(async () =>
  48. {
  49. Thread.Sleep(2000);
  50. while (true)
  51. {
  52. try
  53. {
  54. Present();
  55. }
  56. catch (Exception e)
  57. {
  58. Trace.WriteLine($"Unable to present the items, {e.Message}");
  59. Debugger.Break();
  60. }
  61. finally
  62. {
  63. // present the data every 200ms
  64. await Task.Delay(_presentDelayMillisec);
  65. }
  66. }
  67. });
  68. }
  69. public DelayedPresentRollingObservableCollection(int capacity, int presentDelayMillisec) : this(capacity)
  70. {
  71. _presentDelayMillisec = presentDelayMillisec < 50 ? 50 : presentDelayMillisec;
  72. }
  73. #endregion
  74. #region Properties
  75. public int Capacity { get; }
  76. public int Count
  77. {
  78. get
  79. {
  80. lock (_lockList)
  81. {
  82. return _list?.Count ?? 0;
  83. }
  84. }
  85. }
  86. #endregion
  87. #region Methods
  88. /// <summary>
  89. /// Copy the items from the cache to the presented list and update the UI.
  90. /// </summary>
  91. private void Present()
  92. {
  93. var itemsChanged = new List<T>();
  94. lock (_lockCache)
  95. {
  96. if (_cache.Count <= 0)
  97. return;
  98. itemsChanged.AddRange(_cache);
  99. _cache.Clear();
  100. }
  101. var notifyAction = NotifyCollectionChangedAction.Add;
  102. lock (_lockList)
  103. {
  104. _list.AddRange(itemsChanged);
  105. if (_list.Count >= Capacity)
  106. {
  107. var cntToRemain = Capacity / 2;
  108. _list.RemoveRange(0, _list.Count - cntToRemain);
  109. notifyAction = NotifyCollectionChangedAction.Reset;
  110. }
  111. }
  112. // raise the collection changed event.
  113. SynchronizationContext.SetSynchronizationContext(
  114. new DispatcherSynchronizationContext(Application.Current.Dispatcher));
  115. SynchronizationContext.Current.Post(p1 =>
  116. {
  117. CollectionChanged?.Invoke(
  118. this,
  119. new NotifyCollectionChangedEventArgs(notifyAction,
  120. notifyAction == NotifyCollectionChangedAction.Add ? itemsChanged : null));
  121. }, null);
  122. SynchronizationContext.Current.Post(p1 =>
  123. {
  124. OnPropertyChanged(nameof(Count));
  125. }, null);
  126. }
  127. public void Add(T newItem)
  128. {
  129. lock (_lockCache)
  130. {
  131. _cache.Add(newItem);
  132. }
  133. }
  134. public void Clear()
  135. {
  136. lock (_lockCache)
  137. {
  138. _cache.Clear();
  139. }
  140. lock (_lockList)
  141. {
  142. _list.Clear();
  143. }
  144. }
  145. public IEnumerator<T> GetEnumerator()
  146. {
  147. lock (_lockList)
  148. {
  149. _semListEnumLocker.Wait();
  150. return new SafeEnumerator<T>(_list.GetEnumerator(), _semListEnumLocker);
  151. }
  152. }
  153. IEnumerator IEnumerable.GetEnumerator()
  154. {
  155. lock (_lockList)
  156. {
  157. _semListEnumLocker.Wait();
  158. return new SafeEnumerator<T>(_list.GetEnumerator(), _semListEnumLocker);
  159. }
  160. }
  161. public T this[int index]
  162. {
  163. get
  164. {
  165. if (index < 0 || index >= Count)
  166. throw new ArgumentOutOfRangeException();
  167. lock (_lockList)
  168. {
  169. return _list[index];
  170. }
  171. }
  172. }
  173. #endregion
  174. public event PropertyChangedEventHandler PropertyChanged;
  175. protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  176. {
  177. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  178. }
  179. }
  180. }