IYielder.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 sealed 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() => this;
  38. public bool IsCompleted => false;
  39. public void GetResult()
  40. {
  41. }
  42. [SecurityCritical]
  43. public void UnsafeOnCompleted(Action continuation)
  44. {
  45. _continuation = continuation;
  46. }
  47. public void OnCompleted(Action continuation)
  48. {
  49. _continuation = continuation;
  50. }
  51. public IAwaitable Return(T value)
  52. {
  53. _hasValue = true;
  54. Current = value;
  55. return this;
  56. }
  57. public IAwaitable Break()
  58. {
  59. _stopped = true;
  60. return this;
  61. }
  62. public Yielder<T> GetEnumerator() => this;
  63. public bool MoveNext()
  64. {
  65. if (!_running)
  66. {
  67. _running = true;
  68. _create(this);
  69. }
  70. else
  71. {
  72. _hasValue = false;
  73. _continuation();
  74. }
  75. return !_stopped && _hasValue;
  76. }
  77. public void Reset()
  78. {
  79. throw new NotSupportedException();
  80. }
  81. }
  82. }