Skip to content

Guidance for returning synchronous IEnumerable<T> as IAsyncEnumerable<T> to satisfy interface specification #107845

Answered by RichardD2
DL444 asked this question in Q&A
Discussion options

You must be logged in to vote

One option would be to write an explicit async enumerator to wrap the non-async enumerator (option 3 in your list):

public static class AsyncEnumerable
{
    private sealed class AsAsyncEnumeratorWrapper<T>(IEnumerator<T> enumerator) : IAsyncEnumerator<T>
    {
        private readonly IEnumerator<T> _enumerator = enumerator;

        public ValueTask DisposeAsync()
        {
            _enumerator.Dispose();
            return default;
        }

        public ValueTask<bool> MoveNextAsync()
        {
            bool result = _enumerator.MoveNext();
            return new(result);
        }

        public T Current => _enumerator.Current;
    }

    private sealed class AsAsyncEnumer…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@DL444
Comment options

Answer selected by DL444
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants