SafeEnumerator.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. namespace MECF.Framework.UI.Client.ClientBase.Collections
  5. {
  6. public sealed class SafeEnumerator<T> : IEnumerator<T>
  7. {
  8. #region variables
  9. // this is the (thread-unsafe)
  10. // enumerator of the underlying collection
  11. private readonly IEnumerator<T> _enumeratorInner;
  12. // this is the object we shall lock on.
  13. private readonly SemaphoreSlim _semLocker;
  14. #endregion
  15. public SafeEnumerator(IEnumerator<T> inner, SemaphoreSlim semLocker)
  16. {
  17. // entering lock in constructor
  18. //semLocker.Wait();
  19. _semLocker = semLocker;
  20. _enumeratorInner = inner;
  21. }
  22. #region Implementation of IDisposable
  23. public void Dispose()
  24. {
  25. _semLocker.Release();
  26. }
  27. #endregion
  28. #region Implementation of IEnumerator
  29. // we just delegate actual implementation
  30. // to the inner enumerator, that actually iterates
  31. // over some collection
  32. public bool MoveNext()
  33. {
  34. return _enumeratorInner.MoveNext();
  35. }
  36. public void Reset()
  37. {
  38. _enumeratorInner.Reset();
  39. }
  40. public T Current => _enumeratorInner.Current;
  41. object IEnumerator.Current => Current;
  42. #endregion
  43. }
  44. }