1

Is it possible to just silently terminate an IAsyncEnumerable<T> iterator on exception?

For example, my naive approach was as follows:

public async IAsyncEnumerable<T2> Map<T1, T2>(IAsyncEnumerable<T1> source, Func<T1, T2> map)
{
    try
    {
        await foreach(var elem in source)
            yield return map(elem);
    }
    catch
    {
        yield break;
    }
}

This, however, does not work, because yield return is not allowed inside a try/catch block. The issue is tracked in dotnet repository, but no fix is proposed so far.

Is there any way to rewrite it without having to forgo compiler-generated iterator?

Note: I would like to catch all exceptions, including ones from underlying iterator (e.g. TaskCancelledException from a cancellation token).

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Impworks
  • 2,647
  • 3
  • 25
  • 53
  • Change the tope answer there to finish up with `if (ret == null) yield break; else yield return ret;` – Charlieface Apr 24 '23 at 12:44
  • @Charlieface the approach in your linked issue handles exceptions inside `map` function, but not from the underlying iterator. Unfortunately this is not enough for my case – Impworks Apr 24 '23 at 12:46
  • No the `try` surrounds `MoveNext` so will also catch the underlying iterator. Have you tried it? – Charlieface Apr 24 '23 at 12:58
  • I just posted a [new answer](https://stackoverflow.com/questions/5067188/yield-return-with-try-catch-how-can-i-solve-it/76094252#76094252) to the [older question](https://stackoverflow.com/questions/5067188/yield-return-with-try-catch-how-can-i-solve-it). – Theodor Zoulias Apr 24 '23 at 17:19

0 Answers0