IYielder.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. using System.Security;
  6. #if HAS_AWAIT
  7. namespace System.Linq
  8. {
  9. public interface IYielder<in T>
  10. {
  11. IAwaitable Return(T value);
  12. IAwaitable Break();
  13. }
  14. class Yielder<T> : IYielder<T>, IAwaitable, IAwaiter
  15. {
  16. private readonly Action<Yielder<T>> _create;
  17. private bool _running;
  18. private bool _hasValue;
  19. private T _value;
  20. private bool _stopped;
  21. private Action _continuation;
  22. public Yielder(Action<Yielder<T>> create)
  23. {
  24. _create = create;
  25. }
  26. public IAwaitable Return(T value)
  27. {
  28. _hasValue = true;
  29. _value = value;
  30. return this;
  31. }
  32. public IAwaitable Break()
  33. {
  34. _stopped = true;
  35. return this;
  36. }
  37. public Yielder<T> GetEnumerator()
  38. {
  39. return this;
  40. }
  41. public bool MoveNext()
  42. {
  43. if (!_running)
  44. {
  45. _running = true;
  46. _create(this);
  47. }
  48. else
  49. {
  50. _hasValue = false;
  51. _continuation();
  52. }
  53. return !_stopped && _hasValue;
  54. }
  55. public T Current
  56. {
  57. get
  58. {
  59. return _value;
  60. }
  61. }
  62. public void Reset()
  63. {
  64. throw new NotSupportedException();
  65. }
  66. public IAwaiter GetAwaiter()
  67. {
  68. return this;
  69. }
  70. public bool IsCompleted
  71. {
  72. get { return false; }
  73. }
  74. public void GetResult() { }
  75. [SecurityCritical]
  76. public void UnsafeOnCompleted(Action continuation)
  77. {
  78. _continuation = continuation;
  79. }
  80. public void OnCompleted(Action continuation)
  81. {
  82. _continuation = continuation;
  83. }
  84. }
  85. }
  86. #endif