AsyncIterator.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. internal CancellationToken cancellationToken;
  16. protected AsyncIterator()
  17. {
  18. _threadId = Environment.CurrentManagedThreadId;
  19. }
  20. public IAsyncEnumerator<TSource> GetAsyncEnumerator(CancellationToken cancellationToken)
  21. {
  22. var enumerator = state == AsyncIteratorState.New && _threadId == Environment.CurrentManagedThreadId
  23. ? this
  24. : Clone();
  25. enumerator.state = AsyncIteratorState.Allocated;
  26. enumerator.cancellationToken = cancellationToken;
  27. return enumerator;
  28. }
  29. public virtual ValueTask DisposeAsync()
  30. {
  31. current = default;
  32. state = AsyncIteratorState.Disposed;
  33. return TaskExt.CompletedTask;
  34. }
  35. public TSource Current
  36. {
  37. get
  38. {
  39. if (_currentIsInvalid)
  40. throw new InvalidOperationException("Enumerator is in an invalid state");
  41. return current;
  42. }
  43. }
  44. public async ValueTask<bool> MoveNextAsync()
  45. {
  46. // Note: MoveNext *must* be implemented as an async method to ensure
  47. // that any exceptions thrown from the MoveNextCore call are handled
  48. // by the try/catch, whether they're sync or async
  49. if (state == AsyncIteratorState.Disposed)
  50. {
  51. return false;
  52. }
  53. try
  54. {
  55. var result = await MoveNextCore(cancellationToken).ConfigureAwait(false);
  56. _currentIsInvalid = !result; // if move next is false, invalid otherwise valid
  57. return result;
  58. }
  59. catch
  60. {
  61. _currentIsInvalid = true;
  62. await DisposeAsync().ConfigureAwait(false);
  63. throw;
  64. }
  65. }
  66. public abstract AsyncIterator<TSource> Clone();
  67. protected abstract ValueTask<bool> MoveNextCore(CancellationToken cancellationToken);
  68. }
  69. internal enum AsyncIteratorState
  70. {
  71. New = 0,
  72. Allocated = 1,
  73. Iterating = 2,
  74. Disposed = -1,
  75. }
  76. }