Throw.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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>, IAsyncEnumerator<TValue>
  30. {
  31. private readonly ValueTask<bool> _moveNextThrows;
  32. public TValue Current => default;
  33. public ThrowEnumerable(ValueTask<bool> moveNextThrows)
  34. {
  35. _moveNextThrows = moveNextThrows;
  36. }
  37. public IAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken = default)
  38. {
  39. return this;
  40. }
  41. public ValueTask DisposeAsync()
  42. {
  43. return TaskExt.CompletedTask;
  44. }
  45. public ValueTask<bool> MoveNextAsync()
  46. {
  47. // May we let this fail over and over?
  48. // If so, the class doesn't need extra state
  49. // and thus can be reused without creating an
  50. // async enumerator
  51. return _moveNextThrows;
  52. }
  53. }
  54. }
  55. }