Throw.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;
  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 new ArgumentNullException(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 AsyncEnumerable.CreateEnumerable(
  23. () => AsyncEnumerable.CreateEnumerator<TValue>(
  24. () => moveNextThrows,
  25. current: null,
  26. dispose: null)
  27. );
  28. }
  29. private sealed class ThrowEnumerable<TValue> : IAsyncEnumerable<TValue>
  30. {
  31. private readonly ValueTask<bool> _moveNextThrows;
  32. public ThrowEnumerable(ValueTask<bool> moveNextThrows)
  33. {
  34. _moveNextThrows = moveNextThrows;
  35. }
  36. public IAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken)
  37. {
  38. return new ThrowEnumerator(_moveNextThrows);
  39. }
  40. private sealed class ThrowEnumerator : IAsyncEnumerator<TValue>
  41. {
  42. private ValueTask<bool> _moveNextThrows;
  43. public ThrowEnumerator(ValueTask<bool> moveNextThrows)
  44. {
  45. _moveNextThrows = moveNextThrows;
  46. }
  47. public TValue Current => default;
  48. public ValueTask DisposeAsync()
  49. {
  50. _moveNextThrows = TaskExt.False;
  51. return TaskExt.CompletedTask;
  52. }
  53. public ValueTask<bool> MoveNextAsync()
  54. {
  55. var result = _moveNextThrows;
  56. _moveNextThrows = TaskExt.False;
  57. return result;
  58. }
  59. }
  60. }
  61. }
  62. }