Throw.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. public static partial class AsyncEnumerableEx
  10. {
  11. public static IAsyncEnumerable<TValue> Throw<TValue>(Exception exception)
  12. {
  13. if (exception == null)
  14. throw Error.ArgumentNull(nameof(exception));
  15. #if NO_TASK_FROMEXCEPTION
  16. var tcs = new TaskCompletionSource<bool>();
  17. tcs.TrySetException(exception);
  18. var moveNextThrows = new ValueTask<bool>(tcs.Task);
  19. #else
  20. var moveNextThrows = new ValueTask<bool>(Task.FromException<bool>(exception));
  21. #endif
  22. return new ThrowEnumerable<TValue>(moveNextThrows);
  23. }
  24. private sealed class ThrowEnumerable<TValue> : IAsyncEnumerable<TValue>
  25. {
  26. private readonly ValueTask<bool> _moveNextThrows;
  27. public ThrowEnumerable(ValueTask<bool> moveNextThrows)
  28. {
  29. _moveNextThrows = moveNextThrows;
  30. }
  31. public IAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken)
  32. {
  33. cancellationToken.ThrowIfCancellationRequested(); // NB: [LDM-2018-11-28] Equivalent to async iterator behavior.
  34. return new ThrowEnumerator(_moveNextThrows);
  35. }
  36. private sealed class ThrowEnumerator : IAsyncEnumerator<TValue>
  37. {
  38. private ValueTask<bool> _moveNextThrows;
  39. public ThrowEnumerator(ValueTask<bool> moveNextThrows)
  40. {
  41. _moveNextThrows = moveNextThrows;
  42. }
  43. public TValue Current => default;
  44. public ValueTask DisposeAsync()
  45. {
  46. _moveNextThrows = new ValueTask<bool>(false);
  47. return default;
  48. }
  49. public ValueTask<bool> MoveNextAsync()
  50. {
  51. var result = _moveNextThrows;
  52. _moveNextThrows = new ValueTask<bool>(false);
  53. return result;
  54. }
  55. }
  56. }
  57. }
  58. }