1
0

AsyncEnumerableExtensions.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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.Runtime.CompilerServices;
  6. namespace System.Threading.Tasks
  7. {
  8. namespace System.Threading.Tasks
  9. {
  10. public static class AsyncEnumerableExtensions
  11. {
  12. public static ConfiguredAsyncEnumerable<T> ConfigureAwait<T>(this IAsyncEnumerable<T> enumerable, bool continueOnCapturedContext)
  13. {
  14. if (enumerable == null)
  15. throw Error.ArgumentNull(nameof(enumerable));
  16. return new ConfiguredAsyncEnumerable<T>(enumerable, continueOnCapturedContext);
  17. }
  18. public struct ConfiguredAsyncEnumerable<T>
  19. {
  20. private readonly IAsyncEnumerable<T> _enumerable;
  21. private readonly bool _continueOnCapturedContext;
  22. internal ConfiguredAsyncEnumerable(IAsyncEnumerable<T> enumerable, bool continueOnCapturedContext)
  23. {
  24. _enumerable = enumerable;
  25. _continueOnCapturedContext = continueOnCapturedContext;
  26. }
  27. public ConfiguredAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken) =>
  28. new ConfiguredAsyncEnumerator(_enumerable.GetAsyncEnumerator(cancellationToken), _continueOnCapturedContext);
  29. public struct ConfiguredAsyncEnumerator
  30. {
  31. private readonly IAsyncEnumerator<T> _enumerator;
  32. private readonly bool _continueOnCapturedContext;
  33. internal ConfiguredAsyncEnumerator(IAsyncEnumerator<T> enumerator, bool continueOnCapturedContext)
  34. {
  35. _enumerator = enumerator;
  36. _continueOnCapturedContext = continueOnCapturedContext;
  37. }
  38. public ConfiguredValueTaskAwaitable<bool> MoveNextAsync() =>
  39. _enumerator.MoveNextAsync().ConfigureAwait(_continueOnCapturedContext);
  40. public T Current => _enumerator.Current;
  41. public ConfiguredValueTaskAwaitable DisposeAsync() =>
  42. _enumerator.DisposeAsync().ConfigureAwait(_continueOnCapturedContext);
  43. }
  44. }
  45. }
  46. }
  47. }