Cast.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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.Tasks;
  6. namespace System.Linq
  7. {
  8. public static partial class AsyncEnumerable
  9. {
  10. public static IAsyncEnumerable<TResult> Cast<TResult>(this IAsyncEnumerable<object> source)
  11. {
  12. if (source == null)
  13. throw Error.ArgumentNull(nameof(source));
  14. if (source is IAsyncEnumerable<TResult> typedSource)
  15. {
  16. return typedSource;
  17. }
  18. return new CastAsyncIterator<TResult>(source);
  19. }
  20. private sealed class CastAsyncIterator<TResult> : AsyncIterator<TResult>
  21. {
  22. private readonly IAsyncEnumerable<object> _source;
  23. private IAsyncEnumerator<object> _enumerator;
  24. public CastAsyncIterator(IAsyncEnumerable<object> source)
  25. {
  26. _source = source;
  27. }
  28. public override AsyncIteratorBase<TResult> Clone()
  29. {
  30. return new CastAsyncIterator<TResult>(_source);
  31. }
  32. public override async ValueTask DisposeAsync()
  33. {
  34. if (_enumerator != null)
  35. {
  36. await _enumerator.DisposeAsync().ConfigureAwait(false);
  37. _enumerator = null;
  38. }
  39. await base.DisposeAsync().ConfigureAwait(false);
  40. }
  41. protected override async ValueTask<bool> MoveNextCore()
  42. {
  43. switch (_state)
  44. {
  45. case AsyncIteratorState.Allocated:
  46. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  47. _state = AsyncIteratorState.Iterating;
  48. goto case AsyncIteratorState.Iterating;
  49. case AsyncIteratorState.Iterating:
  50. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  51. {
  52. _current = (TResult)_enumerator.Current;
  53. return true;
  54. }
  55. await DisposeAsync().ConfigureAwait(false);
  56. break;
  57. }
  58. return false;
  59. }
  60. }
  61. }
  62. }