1
0

AsyncIterator.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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.Collections.Generic;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. internal abstract class AsyncIterator<TSource> : IAsyncEnumerable<TSource>, IAsyncEnumerator<TSource>
  10. {
  11. private readonly int threadId;
  12. private bool currentIsInvalid = true;
  13. internal TSource current;
  14. internal AsyncIteratorState state = AsyncIteratorState.New;
  15. protected AsyncIterator()
  16. {
  17. threadId = Environment.CurrentManagedThreadId;
  18. }
  19. public IAsyncEnumerator<TSource> GetAsyncEnumerator()
  20. {
  21. var enumerator = state == AsyncIteratorState.New && threadId == Environment.CurrentManagedThreadId
  22. ? this
  23. : Clone();
  24. enumerator.state = AsyncIteratorState.Allocated;
  25. try
  26. {
  27. enumerator.OnGetEnumerator();
  28. }
  29. catch
  30. {
  31. enumerator.DisposeAsync(); // REVIEW: fire-and-forget?
  32. throw;
  33. }
  34. return enumerator;
  35. }
  36. public virtual Task DisposeAsync()
  37. {
  38. current = default(TSource);
  39. state = AsyncIteratorState.Disposed;
  40. return TaskExt.CompletedTask;
  41. }
  42. public TSource Current
  43. {
  44. get
  45. {
  46. if (currentIsInvalid)
  47. throw new InvalidOperationException("Enumerator is in an invalid state");
  48. return current;
  49. }
  50. }
  51. public async Task<bool> MoveNextAsync()
  52. {
  53. // Note: MoveNext *must* be implemented as an async method to ensure
  54. // that any exceptions thrown from the MoveNextCore call are handled
  55. // by the try/catch, whether they're sync or async
  56. if (state == AsyncIteratorState.Disposed)
  57. {
  58. return false;
  59. }
  60. try
  61. {
  62. var result = await MoveNextCore().ConfigureAwait(false);
  63. currentIsInvalid = !result; // if move next is false, invalid otherwise valid
  64. return result;
  65. }
  66. catch
  67. {
  68. currentIsInvalid = true;
  69. await DisposeAsync().ConfigureAwait(false);
  70. throw;
  71. }
  72. }
  73. public abstract AsyncIterator<TSource> Clone();
  74. protected abstract Task<bool> MoveNextCore();
  75. protected virtual void OnGetEnumerator()
  76. {
  77. }
  78. }
  79. internal enum AsyncIteratorState
  80. {
  81. New = 0,
  82. Allocated = 1,
  83. Iterating = 2,
  84. Disposed = -1,
  85. }
  86. }