Throw.cs 2.5 KB

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