Catch.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. public static IAsyncEnumerable<TSource> Catch<TSource, TException>(this IAsyncEnumerable<TSource> source, Func<TException, IAsyncEnumerable<TSource>> handler)
  14. where TException : Exception
  15. {
  16. if (source == null)
  17. throw Error.ArgumentNull(nameof(source));
  18. if (handler == null)
  19. throw Error.ArgumentNull(nameof(handler));
  20. return new CatchAsyncIterator<TSource, TException>(source, handler);
  21. }
  22. public static IAsyncEnumerable<TSource> Catch<TSource, TException>(this IAsyncEnumerable<TSource> source, Func<TException, ValueTask<IAsyncEnumerable<TSource>>> handler)
  23. where TException : Exception
  24. {
  25. if (source == null)
  26. throw Error.ArgumentNull(nameof(source));
  27. if (handler == null)
  28. throw Error.ArgumentNull(nameof(handler));
  29. return new CatchAsyncIteratorWithTask<TSource, TException>(source, handler);
  30. }
  31. #if !NO_DEEP_CANCELLATION
  32. public static IAsyncEnumerable<TSource> Catch<TSource, TException>(this IAsyncEnumerable<TSource> source, Func<TException, CancellationToken, ValueTask<IAsyncEnumerable<TSource>>> handler)
  33. where TException : Exception
  34. {
  35. if (source == null)
  36. throw Error.ArgumentNull(nameof(source));
  37. if (handler == null)
  38. throw Error.ArgumentNull(nameof(handler));
  39. return new CatchAsyncIteratorWithTaskAndCancellation<TSource, TException>(source, handler);
  40. }
  41. #endif
  42. public static IAsyncEnumerable<TSource> Catch<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
  43. {
  44. if (sources == null)
  45. throw Error.ArgumentNull(nameof(sources));
  46. return CatchCore(sources);
  47. }
  48. public static IAsyncEnumerable<TSource> Catch<TSource>(params IAsyncEnumerable<TSource>[] sources)
  49. {
  50. if (sources == null)
  51. throw Error.ArgumentNull(nameof(sources));
  52. return CatchCore(sources);
  53. }
  54. public static IAsyncEnumerable<TSource> Catch<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
  55. {
  56. if (first == null)
  57. throw Error.ArgumentNull(nameof(first));
  58. if (second == null)
  59. throw Error.ArgumentNull(nameof(second));
  60. return CatchCore(new[] { first, second });
  61. }
  62. private static IAsyncEnumerable<TSource> CatchCore<TSource>(IEnumerable<IAsyncEnumerable<TSource>> sources)
  63. {
  64. return new CatchAsyncIterator<TSource>(sources);
  65. }
  66. private sealed class CatchAsyncIterator<TSource, TException> : AsyncIterator<TSource> where TException : Exception
  67. {
  68. private readonly Func<TException, IAsyncEnumerable<TSource>> _handler;
  69. private readonly IAsyncEnumerable<TSource> _source;
  70. private IAsyncEnumerator<TSource> _enumerator;
  71. private bool _isDone;
  72. public CatchAsyncIterator(IAsyncEnumerable<TSource> source, Func<TException, IAsyncEnumerable<TSource>> handler)
  73. {
  74. Debug.Assert(source != null);
  75. Debug.Assert(handler != null);
  76. _source = source;
  77. _handler = handler;
  78. }
  79. public override AsyncIteratorBase<TSource> Clone()
  80. {
  81. return new CatchAsyncIterator<TSource, TException>(_source, _handler);
  82. }
  83. public override async ValueTask DisposeAsync()
  84. {
  85. if (_enumerator != null)
  86. {
  87. await _enumerator.DisposeAsync().ConfigureAwait(false);
  88. _enumerator = null;
  89. }
  90. await base.DisposeAsync().ConfigureAwait(false);
  91. }
  92. protected override async ValueTask<bool> MoveNextCore()
  93. {
  94. switch (_state)
  95. {
  96. case AsyncIteratorState.Allocated:
  97. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  98. _isDone = false;
  99. _state = AsyncIteratorState.Iterating;
  100. goto case AsyncIteratorState.Iterating;
  101. case AsyncIteratorState.Iterating:
  102. while (true)
  103. {
  104. if (!_isDone)
  105. {
  106. try
  107. {
  108. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  109. {
  110. _current = _enumerator.Current;
  111. return true;
  112. }
  113. }
  114. catch (TException ex)
  115. {
  116. // Note: Ideally we'd dispose of the previous enumerator before
  117. // invoking the handler, but we use this order to preserve
  118. // current behavior
  119. var inner = _handler(ex);
  120. var err = inner.GetAsyncEnumerator(_cancellationToken);
  121. if (_enumerator != null)
  122. {
  123. await _enumerator.DisposeAsync().ConfigureAwait(false);
  124. }
  125. _enumerator = err;
  126. _isDone = true;
  127. continue; // loop so we hit the catch state
  128. }
  129. }
  130. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  131. {
  132. _current = _enumerator.Current;
  133. return true;
  134. }
  135. break; // while
  136. }
  137. break; // case
  138. }
  139. await DisposeAsync().ConfigureAwait(false);
  140. return false;
  141. }
  142. }
  143. private sealed class CatchAsyncIteratorWithTask<TSource, TException> : AsyncIterator<TSource> where TException : Exception
  144. {
  145. private readonly Func<TException, ValueTask<IAsyncEnumerable<TSource>>> _handler;
  146. private readonly IAsyncEnumerable<TSource> _source;
  147. private IAsyncEnumerator<TSource> _enumerator;
  148. private bool _isDone;
  149. public CatchAsyncIteratorWithTask(IAsyncEnumerable<TSource> source, Func<TException, ValueTask<IAsyncEnumerable<TSource>>> handler)
  150. {
  151. Debug.Assert(source != null);
  152. Debug.Assert(handler != null);
  153. _source = source;
  154. _handler = handler;
  155. }
  156. public override AsyncIteratorBase<TSource> Clone()
  157. {
  158. return new CatchAsyncIteratorWithTask<TSource, TException>(_source, _handler);
  159. }
  160. public override async ValueTask DisposeAsync()
  161. {
  162. if (_enumerator != null)
  163. {
  164. await _enumerator.DisposeAsync().ConfigureAwait(false);
  165. _enumerator = null;
  166. }
  167. await base.DisposeAsync().ConfigureAwait(false);
  168. }
  169. protected override async ValueTask<bool> MoveNextCore()
  170. {
  171. switch (_state)
  172. {
  173. case AsyncIteratorState.Allocated:
  174. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  175. _isDone = false;
  176. _state = AsyncIteratorState.Iterating;
  177. goto case AsyncIteratorState.Iterating;
  178. case AsyncIteratorState.Iterating:
  179. while (true)
  180. {
  181. if (!_isDone)
  182. {
  183. try
  184. {
  185. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  186. {
  187. _current = _enumerator.Current;
  188. return true;
  189. }
  190. }
  191. catch (TException ex)
  192. {
  193. // Note: Ideally we'd dispose of the previous enumerator before
  194. // invoking the handler, but we use this order to preserve
  195. // current behavior
  196. var inner = await _handler(ex).ConfigureAwait(false);
  197. var err = inner.GetAsyncEnumerator(_cancellationToken);
  198. if (_enumerator != null)
  199. {
  200. await _enumerator.DisposeAsync().ConfigureAwait(false);
  201. }
  202. _enumerator = err;
  203. _isDone = true;
  204. continue; // loop so we hit the catch state
  205. }
  206. }
  207. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  208. {
  209. _current = _enumerator.Current;
  210. return true;
  211. }
  212. break; // while
  213. }
  214. break; // case
  215. }
  216. await DisposeAsync().ConfigureAwait(false);
  217. return false;
  218. }
  219. }
  220. #if !NO_DEEP_CANCELLATION
  221. private sealed class CatchAsyncIteratorWithTaskAndCancellation<TSource, TException> : AsyncIterator<TSource> where TException : Exception
  222. {
  223. private readonly Func<TException, CancellationToken, ValueTask<IAsyncEnumerable<TSource>>> _handler;
  224. private readonly IAsyncEnumerable<TSource> _source;
  225. private IAsyncEnumerator<TSource> _enumerator;
  226. private bool _isDone;
  227. public CatchAsyncIteratorWithTaskAndCancellation(IAsyncEnumerable<TSource> source, Func<TException, CancellationToken, ValueTask<IAsyncEnumerable<TSource>>> handler)
  228. {
  229. Debug.Assert(source != null);
  230. Debug.Assert(handler != null);
  231. _source = source;
  232. _handler = handler;
  233. }
  234. public override AsyncIteratorBase<TSource> Clone()
  235. {
  236. return new CatchAsyncIteratorWithTaskAndCancellation<TSource, TException>(_source, _handler);
  237. }
  238. public override async ValueTask DisposeAsync()
  239. {
  240. if (_enumerator != null)
  241. {
  242. await _enumerator.DisposeAsync().ConfigureAwait(false);
  243. _enumerator = null;
  244. }
  245. await base.DisposeAsync().ConfigureAwait(false);
  246. }
  247. protected override async ValueTask<bool> MoveNextCore()
  248. {
  249. switch (_state)
  250. {
  251. case AsyncIteratorState.Allocated:
  252. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  253. _isDone = false;
  254. _state = AsyncIteratorState.Iterating;
  255. goto case AsyncIteratorState.Iterating;
  256. case AsyncIteratorState.Iterating:
  257. while (true)
  258. {
  259. if (!_isDone)
  260. {
  261. try
  262. {
  263. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  264. {
  265. _current = _enumerator.Current;
  266. return true;
  267. }
  268. }
  269. catch (TException ex)
  270. {
  271. // Note: Ideally we'd dispose of the previous enumerator before
  272. // invoking the handler, but we use this order to preserve
  273. // current behavior
  274. var inner = await _handler(ex, _cancellationToken).ConfigureAwait(false);
  275. var err = inner.GetAsyncEnumerator(_cancellationToken);
  276. if (_enumerator != null)
  277. {
  278. await _enumerator.DisposeAsync().ConfigureAwait(false);
  279. }
  280. _enumerator = err;
  281. _isDone = true;
  282. continue; // loop so we hit the catch state
  283. }
  284. }
  285. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  286. {
  287. _current = _enumerator.Current;
  288. return true;
  289. }
  290. break; // while
  291. }
  292. break; // case
  293. }
  294. await DisposeAsync().ConfigureAwait(false);
  295. return false;
  296. }
  297. }
  298. #endif
  299. private sealed class CatchAsyncIterator<TSource> : AsyncIterator<TSource>
  300. {
  301. private readonly IEnumerable<IAsyncEnumerable<TSource>> _sources;
  302. private IAsyncEnumerator<TSource> _enumerator;
  303. private ExceptionDispatchInfo _error;
  304. private IEnumerator<IAsyncEnumerable<TSource>> _sourcesEnumerator;
  305. public CatchAsyncIterator(IEnumerable<IAsyncEnumerable<TSource>> sources)
  306. {
  307. Debug.Assert(sources != null);
  308. _sources = sources;
  309. }
  310. public override AsyncIteratorBase<TSource> Clone()
  311. {
  312. return new CatchAsyncIterator<TSource>(_sources);
  313. }
  314. public override async ValueTask DisposeAsync()
  315. {
  316. if (_sourcesEnumerator != null)
  317. {
  318. _sourcesEnumerator.Dispose();
  319. _sourcesEnumerator = null;
  320. }
  321. if (_enumerator != null)
  322. {
  323. await _enumerator.DisposeAsync().ConfigureAwait(false);
  324. _enumerator = null;
  325. }
  326. _error = null;
  327. await base.DisposeAsync().ConfigureAwait(false);
  328. }
  329. protected override async ValueTask<bool> MoveNextCore()
  330. {
  331. switch (_state)
  332. {
  333. case AsyncIteratorState.Allocated:
  334. _sourcesEnumerator = _sources.GetEnumerator();
  335. _state = AsyncIteratorState.Iterating;
  336. goto case AsyncIteratorState.Iterating;
  337. case AsyncIteratorState.Iterating:
  338. while (true)
  339. {
  340. if (_enumerator == null)
  341. {
  342. if (!_sourcesEnumerator.MoveNext())
  343. {
  344. // only throw if we have an error on the last one
  345. _error?.Throw();
  346. break; // done, nothing else to do
  347. }
  348. _error = null;
  349. _enumerator = _sourcesEnumerator.Current.GetAsyncEnumerator(_cancellationToken);
  350. }
  351. try
  352. {
  353. if (await _enumerator.MoveNextAsync().ConfigureAwait(false))
  354. {
  355. _current = _enumerator.Current;
  356. return true;
  357. }
  358. }
  359. catch (Exception ex)
  360. {
  361. // Done with the current one, go to the next
  362. await _enumerator.DisposeAsync().ConfigureAwait(false);
  363. _enumerator = null;
  364. _error = ExceptionDispatchInfo.Capture(ex);
  365. continue;
  366. }
  367. break; // while
  368. }
  369. break; // case
  370. }
  371. await DisposeAsync().ConfigureAwait(false);
  372. return false;
  373. }
  374. }
  375. }
  376. }