Search code examples
c#.netlinqasynchronousiasyncenumerable

Read only first item from IAsyncEnumerable, then cancel


When consuming IAsyncEnumerable<T>, is it possible to just read first item from the stream and then cancel the operation and return it? Something like a FirstOrDefault on IEnumerable<T>?

Cheers


Solution

  • See this Microsoft Tutorial on using IAsyncEnumerable<T>. You can get the IAsyncEnumerator<T> and use it to get the first item.

    await using (var enumerator = myAsyncEnumerable.GetAsyncEnumerator()){
        // If MoveNextAsync() returns false, the enumerator is empty.
        var first = await enumerator.MoveNextAsync() ? enumerator.Current : default;
    }