IYielder.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Runtime.CompilerServices;
  5. #if HAS_AWAIT
  6. namespace System.Linq
  7. {
  8. public interface IYielder<in T>
  9. {
  10. IAwaitable Return(T value);
  11. IAwaitable Break();
  12. }
  13. class Yielder<T> : IYielder<T>, IAwaitable, IAwaiter, ICriticalNotifyCompletion
  14. {
  15. private readonly Action<Yielder<T>> _create;
  16. private bool _running;
  17. private bool _hasValue;
  18. private T _value;
  19. private bool _stopped;
  20. private Action _continuation;
  21. public Yielder(Action<Yielder<T>> create)
  22. {
  23. _create = create;
  24. }
  25. public IAwaitable Return(T value)
  26. {
  27. _hasValue = true;
  28. _value = value;
  29. return this;
  30. }
  31. public IAwaitable Break()
  32. {
  33. _stopped = true;
  34. return this;
  35. }
  36. public Yielder<T> GetEnumerator()
  37. {
  38. return this;
  39. }
  40. public bool MoveNext()
  41. {
  42. if (!_running)
  43. {
  44. _running = true;
  45. _create(this);
  46. }
  47. else
  48. {
  49. _hasValue = false;
  50. _continuation();
  51. }
  52. return !_stopped && _hasValue;
  53. }
  54. public T Current
  55. {
  56. get
  57. {
  58. return _value;
  59. }
  60. }
  61. public void Reset()
  62. {
  63. throw new NotSupportedException();
  64. }
  65. public IAwaiter GetAwaiter()
  66. {
  67. return this;
  68. }
  69. public bool IsCompleted
  70. {
  71. get { return false; }
  72. }
  73. public void UnsafeOnCompleted(Action continuation)
  74. {
  75. _continuation = continuation;
  76. }
  77. public void GetResult() { }
  78. public void OnCompleted(Action continuation)
  79. {
  80. _continuation = continuation;
  81. }
  82. }
  83. }
  84. #endif