Catch.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  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.Diagnostics;
  6. using System.Runtime.ExceptionServices;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace System.Linq
  10. {
  11. public static partial class AsyncEnumerableEx
  12. {
  13. // REVIEW: All Catch operators may catch OperationCanceledException due to cancellation of the enumeration
  14. // of the source. Should we explicitly avoid handling this? E.g. as follows:
  15. //
  16. // catch (TException ex) when(!(ex is OperationCanceledException oce && oce.CancellationToken == cancellationToken))
  17. public static IAsyncEnumerable<TSource> Catch<TSource, TException>(this IAsyncEnumerable<TSource> source, Func<TException, IAsyncEnumerable<TSource>> handler)
  18. where TException : Exception
  19. {
  20. if (source == null)
  21. throw Error.ArgumentNull(nameof(source));
  22. if (handler == null)
  23. throw Error.ArgumentNull(nameof(handler));
  24. #if USE_ASYNC_ITERATOR
  25. return AsyncEnumerable.Create(Core);
  26. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  27. {
  28. // REVIEW: This implementation mirrors the Ix implementation, which does not protect GetEnumerator
  29. // using the try statement either. A more trivial implementation would use await foreach
  30. // and protect the entire loop using a try statement, with two breaking changes:
  31. //
  32. // - Also protecting the call to GetAsyncEnumerator by the try statement.
  33. // - Invocation of the handler after disposal of the failed first sequence.
  34. var err = default(IAsyncEnumerable<TSource>);
  35. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  36. {
  37. while (true)
  38. {
  39. var c = default(TSource);
  40. try
  41. {
  42. if (!await e.MoveNextAsync())
  43. break;
  44. c = e.Current;
  45. }
  46. catch (TException ex)
  47. {
  48. err = handler(ex);
  49. break;
  50. }
  51. yield return c;
  52. }
  53. }
  54. if (err != null)
  55. {
  56. await foreach (var item in AsyncEnumerableExtensions.WithCancellation(err, cancellationToken).ConfigureAwait(false))
  57. {
  58. yield return item;
  59. }
  60. }
  61. }
  62. #else
  63. return new CatchAsyncIterator<TSource, TException>(source, handler);
  64. #endif
  65. }
  66. public static IAsyncEnumerable<TSource> Catch<TSource, TException>(this IAsyncEnumerable<TSource> source, Func<TException, ValueTask<IAsyncEnumerable<TSource>>> handler)
  67. where TException : Exception
  68. {
  69. if (source == null)
  70. throw Error.ArgumentNull(nameof(source));
  71. if (handler == null)
  72. throw Error.ArgumentNull(nameof(handler));
  73. #if USE_ASYNC_ITERATOR
  74. return AsyncEnumerable.Create(Core);
  75. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  76. {
  77. // REVIEW: This implementation mirrors the Ix implementation, which does not protect GetEnumerator
  78. // using the try statement either. A more trivial implementation would use await foreach
  79. // and protect the entire loop using a try statement, with two breaking changes:
  80. //
  81. // - Also protecting the call to GetAsyncEnumerator by the try statement.
  82. // - Invocation of the handler after disposal of the failed first sequence.
  83. var err = default(IAsyncEnumerable<TSource>);
  84. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  85. {
  86. while (true)
  87. {
  88. var c = default(TSource);
  89. try
  90. {
  91. if (!await e.MoveNextAsync())
  92. break;
  93. c = e.Current;
  94. }
  95. catch (TException ex)
  96. {
  97. err = await handler(ex).ConfigureAwait(false);
  98. break;
  99. }
  100. yield return c;
  101. }
  102. }
  103. if (err != null)
  104. {
  105. await foreach (var item in AsyncEnumerableExtensions.WithCancellation(err, cancellationToken).ConfigureAwait(false))
  106. {
  107. yield return item;
  108. }
  109. }
  110. }
  111. #else
  112. return new CatchAsyncIteratorWithTask<TSource, TException>(source, handler);
  113. #endif
  114. }
  115. #if !NO_DEEP_CANCELLATION
  116. public static IAsyncEnumerable<TSource> Catch<TSource, TException>(this IAsyncEnumerable<TSource> source, Func<TException, CancellationToken, ValueTask<IAsyncEnumerable<TSource>>> handler)
  117. where TException : Exception
  118. {
  119. if (source == null)
  120. throw Error.ArgumentNull(nameof(source));
  121. if (handler == null)
  122. throw Error.ArgumentNull(nameof(handler));
  123. #if USE_ASYNC_ITERATOR
  124. return AsyncEnumerable.Create(Core);
  125. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  126. {
  127. // REVIEW: This implementation mirrors the Ix implementation, which does not protect GetEnumerator
  128. // using the try statement either. A more trivial implementation would use await foreach
  129. // and protect the entire loop using a try statement, with two breaking changes:
  130. //
  131. // - Also protecting the call to GetAsyncEnumerator by the try statement.
  132. // - Invocation of the handler after disposal of the failed first sequence.
  133. var err = default(IAsyncEnumerable<TSource>);
  134. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  135. {
  136. while (true)
  137. {
  138. var c = default(TSource);
  139. try
  140. {
  141. if (!await e.MoveNextAsync())
  142. break;
  143. c = e.Current;
  144. }
  145. catch (TException ex)
  146. {
  147. err = await handler(ex, cancellationToken).ConfigureAwait(false);
  148. break;
  149. }
  150. yield return c;
  151. }
  152. }
  153. if (err != null)
  154. {
  155. await foreach (var item in AsyncEnumerableExtensions.WithCancellation(err, cancellationToken).ConfigureAwait(false))
  156. {
  157. yield return item;
  158. }
  159. }
  160. }
  161. #else
  162. return new CatchAsyncIteratorWithTaskAndCancellation<TSource, TException>(source, handler);
  163. #endif
  164. }
  165. #endif
  166. public static IAsyncEnumerable<TSource> Catch<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
  167. {
  168. if (sources == null)
  169. throw Error.ArgumentNull(nameof(sources));
  170. return CatchCore(sources);
  171. }
  172. public static IAsyncEnumerable<TSource> Catch<TSource>(params IAsyncEnumerable<TSource>[] sources)
  173. {
  174. if (sources == null)
  175. throw Error.ArgumentNull(nameof(sources));
  176. return CatchCore(sources);
  177. }
  178. public static IAsyncEnumerable<TSource> Catch<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
  179. {
  180. if (first == null)
  181. throw Error.ArgumentNull(nameof(first));
  182. if (second == null)
  183. throw Error.ArgumentNull(nameof(second));
  184. return CatchCore(new[] { first, second });
  185. }
  186. private static IAsyncEnumerable<TSource> CatchCore<TSource>(IEnumerable<IAsyncEnumerable<TSource>> sources)
  187. {
  188. #if USE_ASYNC_ITERATOR
  189. return AsyncEnumerable.Create(Core);
  190. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  191. {
  192. var error = default(ExceptionDispatchInfo);
  193. foreach (var source in sources)
  194. {
  195. await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false))
  196. {
  197. error = null;
  198. while (true)
  199. {
  200. var c = default(TSource);
  201. try
  202. {
  203. if (!await e.MoveNextAsync())
  204. break;
  205. c = e.Current;
  206. }
  207. catch (Exception ex)
  208. {
  209. error = ExceptionDispatchInfo.Capture(ex);
  210. break;
  211. }
  212. yield return c;
  213. }
  214. if (error == null)
  215. break;
  216. }
  217. }
  218. error?.Throw();
  219. }
  220. #else
  221. return new CatchAsyncIterator<TSource>(sources);
  222. #endif
  223. }
  224. #if !USE_ASYNC_ITERATOR
  225. private sealed class CatchAsyncIterator<TSource, TException> : AsyncIterator<TSource> where TException : Exception
  226. {
  227. private readonly Func<TException, IAsyncEnumerable<TSource>> _handler;
  228. private readonly IAsyncEnumerable<TSource> _source;
  229. private IAsyncEnumerator<TSource> _enumerator;
  230. private bool _isDone;
  231. public CatchAsyncIterator(IAsyncEnumerable<TSource> source, Func<TException, IAsyncEnumerable<TSource>> handler)
  232. {
  233. Debug.Assert(source != null);
  234. Debug.Assert(handler != null);
  235. _source = source;
  236. _handler = handler;
  237. }
  238. public override AsyncIteratorBase<TSource> Clone()
  239. {
  240. return new CatchAsyncIterator<TSource, TException>(_source, _handler);
  241. }
  242. public override async ValueTask DisposeAsync()
  243. {
  244. if (_enumerator != null)
  245. {
  246. await _enumerator.DisposeAsync().ConfigureAwait(false);
  247. _enumerator = null;
  248. }
  249. await base.DisposeAsync().ConfigureAwait(false);
  250. }
  251. protected override async ValueTask<bool> MoveNextCore()
  252. {
  253. switch (_state)
  254. {
  255. case AsyncIteratorState.Allocated:
  256. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  257. _isDone = false;
  258. _state = AsyncIteratorState.Iterating;
  259. goto case AsyncIteratorState.Iterating;
  260. case AsyncIteratorState.Iterating:
  261. while (true)
  262. {
  263. if (!_isDone)
  264. {
  265. try
  266. {
  267. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  268. {
  269. _current = _enumerator.Current;
  270. return true;
  271. }
  272. }
  273. catch (TException ex)
  274. {
  275. // Note: Ideally we'd dispose of the previous enumerator before
  276. // invoking the handler, but we use this order to preserve
  277. // current behavior
  278. var inner = _handler(ex);
  279. var err = inner.GetAsyncEnumerator(_cancellationToken);
  280. if (_enumerator != null)
  281. {
  282. await _enumerator.DisposeAsync().ConfigureAwait(false);
  283. }
  284. _enumerator = err;
  285. _isDone = true;
  286. continue; // loop so we hit the catch state
  287. }
  288. }
  289. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  290. {
  291. _current = _enumerator.Current;
  292. return true;
  293. }
  294. break; // while
  295. }
  296. break; // case
  297. }
  298. await DisposeAsync().ConfigureAwait(false);
  299. return false;
  300. }
  301. }
  302. private sealed class CatchAsyncIteratorWithTask<TSource, TException> : AsyncIterator<TSource> where TException : Exception
  303. {
  304. private readonly Func<TException, ValueTask<IAsyncEnumerable<TSource>>> _handler;
  305. private readonly IAsyncEnumerable<TSource> _source;
  306. private IAsyncEnumerator<TSource> _enumerator;
  307. private bool _isDone;
  308. public CatchAsyncIteratorWithTask(IAsyncEnumerable<TSource> source, Func<TException, ValueTask<IAsyncEnumerable<TSource>>> handler)
  309. {
  310. Debug.Assert(source != null);
  311. Debug.Assert(handler != null);
  312. _source = source;
  313. _handler = handler;
  314. }
  315. public override AsyncIteratorBase<TSource> Clone()
  316. {
  317. return new CatchAsyncIteratorWithTask<TSource, TException>(_source, _handler);
  318. }
  319. public override async ValueTask DisposeAsync()
  320. {
  321. if (_enumerator != null)
  322. {
  323. await _enumerator.DisposeAsync().ConfigureAwait(false);
  324. _enumerator = null;
  325. }
  326. await base.DisposeAsync().ConfigureAwait(false);
  327. }
  328. protected override async ValueTask<bool> MoveNextCore()
  329. {
  330. switch (_state)
  331. {
  332. case AsyncIteratorState.Allocated:
  333. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  334. _isDone = false;
  335. _state = AsyncIteratorState.Iterating;
  336. goto case AsyncIteratorState.Iterating;
  337. case AsyncIteratorState.Iterating:
  338. while (true)
  339. {
  340. if (!_isDone)
  341. {
  342. try
  343. {
  344. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  345. {
  346. _current = _enumerator.Current;
  347. return true;
  348. }
  349. }
  350. catch (TException ex)
  351. {
  352. // Note: Ideally we'd dispose of the previous enumerator before
  353. // invoking the handler, but we use this order to preserve
  354. // current behavior
  355. var inner = await _handler(ex).ConfigureAwait(false);
  356. var err = inner.GetAsyncEnumerator(_cancellationToken);
  357. if (_enumerator != null)
  358. {
  359. await _enumerator.DisposeAsync().ConfigureAwait(false);
  360. }
  361. _enumerator = err;
  362. _isDone = true;
  363. continue; // loop so we hit the catch state
  364. }
  365. }
  366. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  367. {
  368. _current = _enumerator.Current;
  369. return true;
  370. }
  371. break; // while
  372. }
  373. break; // case
  374. }
  375. await DisposeAsync().ConfigureAwait(false);
  376. return false;
  377. }
  378. }
  379. #if !NO_DEEP_CANCELLATION
  380. private sealed class CatchAsyncIteratorWithTaskAndCancellation<TSource, TException> : AsyncIterator<TSource> where TException : Exception
  381. {
  382. private readonly Func<TException, CancellationToken, ValueTask<IAsyncEnumerable<TSource>>> _handler;
  383. private readonly IAsyncEnumerable<TSource> _source;
  384. private IAsyncEnumerator<TSource> _enumerator;
  385. private bool _isDone;
  386. public CatchAsyncIteratorWithTaskAndCancellation(IAsyncEnumerable<TSource> source, Func<TException, CancellationToken, ValueTask<IAsyncEnumerable<TSource>>> handler)
  387. {
  388. Debug.Assert(source != null);
  389. Debug.Assert(handler != null);
  390. _source = source;
  391. _handler = handler;
  392. }
  393. public override AsyncIteratorBase<TSource> Clone()
  394. {
  395. return new CatchAsyncIteratorWithTaskAndCancellation<TSource, TException>(_source, _handler);
  396. }
  397. public override async ValueTask DisposeAsync()
  398. {
  399. if (_enumerator != null)
  400. {
  401. await _enumerator.DisposeAsync().ConfigureAwait(false);
  402. _enumerator = null;
  403. }
  404. await base.DisposeAsync().ConfigureAwait(false);
  405. }
  406. protected override async ValueTask<bool> MoveNextCore()
  407. {
  408. switch (_state)
  409. {
  410. case AsyncIteratorState.Allocated:
  411. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  412. _isDone = false;
  413. _state = AsyncIteratorState.Iterating;
  414. goto case AsyncIteratorState.Iterating;
  415. case AsyncIteratorState.Iterating:
  416. while (true)
  417. {
  418. if (!_isDone)
  419. {
  420. try
  421. {
  422. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  423. {
  424. _current = _enumerator.Current;
  425. return true;
  426. }
  427. }
  428. catch (TException ex)
  429. {
  430. // Note: Ideally we'd dispose of the previous enumerator before
  431. // invoking the handler, but we use this order to preserve
  432. // current behavior
  433. var inner = await _handler(ex, _cancellationToken).ConfigureAwait(false);
  434. var err = inner.GetAsyncEnumerator(_cancellationToken);
  435. if (_enumerator != null)
  436. {
  437. await _enumerator.DisposeAsync().ConfigureAwait(false);
  438. }
  439. _enumerator = err;
  440. _isDone = true;
  441. continue; // loop so we hit the catch state
  442. }
  443. }
  444. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  445. {
  446. _current = _enumerator.Current;
  447. return true;
  448. }
  449. break; // while
  450. }
  451. break; // case
  452. }
  453. await DisposeAsync().ConfigureAwait(false);
  454. return false;
  455. }
  456. }
  457. #endif
  458. private sealed class CatchAsyncIterator<TSource> : AsyncIterator<TSource>
  459. {
  460. private readonly IEnumerable<IAsyncEnumerable<TSource>> _sources;
  461. private IAsyncEnumerator<TSource> _enumerator;
  462. private ExceptionDispatchInfo _error;
  463. private IEnumerator<IAsyncEnumerable<TSource>> _sourcesEnumerator;
  464. public CatchAsyncIterator(IEnumerable<IAsyncEnumerable<TSource>> sources)
  465. {
  466. Debug.Assert(sources != null);
  467. _sources = sources;
  468. }
  469. public override AsyncIteratorBase<TSource> Clone()
  470. {
  471. return new CatchAsyncIterator<TSource>(_sources);
  472. }
  473. public override async ValueTask DisposeAsync()
  474. {
  475. if (_sourcesEnumerator != null)
  476. {
  477. _sourcesEnumerator.Dispose();
  478. _sourcesEnumerator = null;
  479. }
  480. if (_enumerator != null)
  481. {
  482. await _enumerator.DisposeAsync().ConfigureAwait(false);
  483. _enumerator = null;
  484. }
  485. _error = null;
  486. await base.DisposeAsync().ConfigureAwait(false);
  487. }
  488. protected override async ValueTask<bool> MoveNextCore()
  489. {
  490. switch (_state)
  491. {
  492. case AsyncIteratorState.Allocated:
  493. _sourcesEnumerator = _sources.GetEnumerator();
  494. _state = AsyncIteratorState.Iterating;
  495. goto case AsyncIteratorState.Iterating;
  496. case AsyncIteratorState.Iterating:
  497. while (true)
  498. {
  499. if (_enumerator == null)
  500. {
  501. if (!_sourcesEnumerator.MoveNext())
  502. {
  503. // only throw if we have an error on the last one
  504. _error?.Throw();
  505. break; // done, nothing else to do
  506. }
  507. _error = null;
  508. _enumerator = _sourcesEnumerator.Current.GetAsyncEnumerator(_cancellationToken);
  509. }
  510. try
  511. {
  512. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  513. {
  514. _current = _enumerator.Current;
  515. return true;
  516. }
  517. }
  518. catch (Exception ex)
  519. {
  520. // Done with the current one, go to the next
  521. await _enumerator.DisposeAsync().ConfigureAwait(false);
  522. _enumerator = null;
  523. _error = ExceptionDispatchInfo.Capture(ex);
  524. continue;
  525. }
  526. break; // while
  527. }
  528. break; // case
  529. }
  530. await DisposeAsync().ConfigureAwait(false);
  531. return false;
  532. }
  533. }
  534. #endif
  535. }
  536. }