How to properly manage an IAsyncEnumerable that returns IDisposables

55 views Asked by At

I have IAsyncEnumerable<Segment> RetrieveSegments() where Segment : IDisposable.

My question is how to properly manage this such that the Segments get disposed at the end of each iteration.

The current solution I have is this:

await foreach (var segment in RetrieveSegments())
{
    try 
    {
        // Do stuff
    }
    finally
    {
        segment?.Dispose();
    }
}

Is this good enough, there is no await foreach (using var segment in RetrieveSegments()).

Or is there perhaps some better way to avoid this all together, the Segment is IDisposable because within it it holds a Stream.

I would like your opinions on this, as I think my current solution can lead to things not being disposed if used improperly.

0

There are 0 answers