OnErrorResumeNext.cs 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace System.Linq
  10. {
  11. public static partial class AsyncEnumerable
  12. {
  13. public static IAsyncEnumerable<TSource> OnErrorResumeNext<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
  14. {
  15. if (first == null)
  16. throw new ArgumentNullException(nameof(first));
  17. if (second == null)
  18. throw new ArgumentNullException(nameof(second));
  19. return OnErrorResumeNext_(new[] {first, second});
  20. }
  21. public static IAsyncEnumerable<TSource> OnErrorResumeNext<TSource>(params IAsyncEnumerable<TSource>[] sources)
  22. {
  23. if (sources == null)
  24. throw new ArgumentNullException(nameof(sources));
  25. return OnErrorResumeNext_(sources);
  26. }
  27. public static IAsyncEnumerable<TSource> OnErrorResumeNext<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
  28. {
  29. if (sources == null)
  30. throw new ArgumentNullException(nameof(sources));
  31. return OnErrorResumeNext_(sources);
  32. }
  33. private static IAsyncEnumerable<TSource> OnErrorResumeNext_<TSource>(IEnumerable<IAsyncEnumerable<TSource>> sources)
  34. {
  35. return CreateEnumerable(
  36. () =>
  37. {
  38. var se = sources.GetEnumerator();
  39. var e = default(IAsyncEnumerator<TSource>);
  40. var cts = new CancellationTokenDisposable();
  41. var a = new AssignableDisposable();
  42. var d = Disposable.Create(cts, se, a);
  43. var f = default(Func<CancellationToken, Task<bool>>);
  44. f = async ct =>
  45. {
  46. if (e == null)
  47. {
  48. var b = false;
  49. b = se.MoveNext();
  50. if (b)
  51. e = se.Current.GetEnumerator();
  52. else
  53. {
  54. return false;
  55. }
  56. a.Disposable = e;
  57. }
  58. try
  59. {
  60. if (await e.MoveNext(ct)
  61. .ConfigureAwait(false))
  62. {
  63. return true;
  64. }
  65. }
  66. catch
  67. {
  68. // ignore
  69. }
  70. e.Dispose();
  71. e = null;
  72. return await f(ct)
  73. .ConfigureAwait(false);
  74. };
  75. return CreateEnumerator(
  76. f,
  77. () => e.Current,
  78. d.Dispose,
  79. a
  80. );
  81. });
  82. }
  83. }
  84. }