OnErrorResumeNext.cs 3.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 Create(() =>
  36. {
  37. var se = sources.GetEnumerator();
  38. var e = default(IAsyncEnumerator<TSource>);
  39. var cts = new CancellationTokenDisposable();
  40. var a = new AssignableDisposable();
  41. var d = Disposable.Create(cts, se, a);
  42. var f = default(Func<CancellationToken, Task<bool>>);
  43. f = async ct =>
  44. {
  45. if (e == null)
  46. {
  47. var b = false;
  48. b = se.MoveNext();
  49. if (b)
  50. e = se.Current.GetEnumerator();
  51. else
  52. {
  53. return false;
  54. }
  55. a.Disposable = e;
  56. }
  57. try
  58. {
  59. if (await e.MoveNext(ct)
  60. .ConfigureAwait(false))
  61. {
  62. return true;
  63. }
  64. }
  65. catch
  66. {
  67. // ignore
  68. }
  69. e.Dispose();
  70. e = null;
  71. return await f(ct)
  72. .ConfigureAwait(false);
  73. };
  74. return Create(
  75. f,
  76. () => e.Current,
  77. d.Dispose,
  78. a
  79. );
  80. });
  81. }
  82. }
  83. }