Yielder.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. internal sealed class Yielder<T> : IYielder<T>, IAwaitable, IAwaiter
  8. {
  9. private readonly Action<Yielder<T>> _create;
  10. private Action? _continuation;
  11. private bool _hasValue;
  12. private bool _running;
  13. private bool _stopped;
  14. public Yielder(Action<Yielder<T>> create)
  15. {
  16. _create = create;
  17. Current = default!;
  18. }
  19. public T Current { get; private set; }
  20. public IAwaiter GetAwaiter() => this;
  21. public bool IsCompleted => false;
  22. public void GetResult()
  23. {
  24. }
  25. [SecurityCritical]
  26. public void UnsafeOnCompleted(Action continuation)
  27. {
  28. _continuation = continuation;
  29. }
  30. public void OnCompleted(Action continuation)
  31. {
  32. _continuation = continuation;
  33. }
  34. public IAwaitable Return(T value)
  35. {
  36. _hasValue = true;
  37. Current = value;
  38. return this;
  39. }
  40. public IAwaitable Break()
  41. {
  42. _stopped = true;
  43. return this;
  44. }
  45. public Yielder<T> GetEnumerator() => this;
  46. public bool MoveNext()
  47. {
  48. if (!_running)
  49. {
  50. _running = true;
  51. _create(this);
  52. }
  53. else
  54. {
  55. _hasValue = false;
  56. _continuation!();
  57. }
  58. return !_stopped && _hasValue;
  59. }
  60. public void Reset() => throw new NotSupportedException();
  61. }
  62. }