IYielder.cs 2.7 KB

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