IYielder.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if HAS_AWAIT
  3. using System.Security;
  4. namespace System.Linq
  5. {
  6. /// <summary>
  7. /// Interface for yielding elements to enumerator.
  8. /// </summary>
  9. /// <typeparam name="T">Type of the elements yielded to an enumerator.</typeparam>
  10. public interface IYielder<in T>
  11. {
  12. /// <summary>
  13. /// Yields a value to the enumerator.
  14. /// </summary>
  15. /// <param name="value">Value to yield return.</param>
  16. /// <returns>Awaitable object for use in an asynchronous method.</returns>
  17. IAwaitable Return(T value);
  18. /// <summary>
  19. /// Stops the enumeration.
  20. /// </summary>
  21. /// <returns>Awaitable object for use in an asynchronous method.</returns>
  22. IAwaitable Break();
  23. }
  24. class Yielder<T> : IYielder<T>, IAwaitable, IAwaiter
  25. {
  26. private readonly Action<Yielder<T>> _create;
  27. private bool _running;
  28. private bool _hasValue;
  29. private T _value;
  30. private bool _stopped;
  31. private Action _continuation;
  32. public Yielder(Action<Yielder<T>> create)
  33. {
  34. _create = create;
  35. }
  36. public IAwaitable Return(T value)
  37. {
  38. _hasValue = true;
  39. _value = value;
  40. return this;
  41. }
  42. public IAwaitable Break()
  43. {
  44. _stopped = true;
  45. return this;
  46. }
  47. public Yielder<T> GetEnumerator()
  48. {
  49. return this;
  50. }
  51. public bool MoveNext()
  52. {
  53. if (!_running)
  54. {
  55. _running = true;
  56. _create(this);
  57. }
  58. else
  59. {
  60. _hasValue = false;
  61. _continuation();
  62. }
  63. return !_stopped && _hasValue;
  64. }
  65. public T Current
  66. {
  67. get
  68. {
  69. return _value;
  70. }
  71. }
  72. public void Reset()
  73. {
  74. throw new NotSupportedException();
  75. }
  76. public IAwaiter GetAwaiter()
  77. {
  78. return this;
  79. }
  80. public bool IsCompleted
  81. {
  82. get { return false; }
  83. }
  84. public void GetResult() { }
  85. [SecurityCritical]
  86. public void UnsafeOnCompleted(Action continuation)
  87. {
  88. _continuation = continuation;
  89. }
  90. public void OnCompleted(Action continuation)
  91. {
  92. _continuation = continuation;
  93. }
  94. }
  95. }
  96. #endif