1
0

IYielder.cs 2.6 KB

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