Yielder.cs 1.8 KB

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