How can I run a async enumerator method synchronously and store it as an IEnumerable?

0

Issue

I have an async method that returns an IAsyncEnumerable using yield. In some cases, it may be needed to get the items synchronously so I want to make another method for this that returns IEnumerable by running the existing method synchronously in order to avoid duplicate code.

async IAsyncEnumerable<Foo> GetItemsAsync()
{
    yield return ...
}

IEnumerable<Foo> GetItems() => GetItemsAsync() // Run shyncronously

I read plenty solutions about running async methods synchronously using techniques like the Task.RunSynchronously or simply calling it in a sync context and ignoring the warning. However, it seems neither of these is possible in the case of async enumerables. The interface features no RunSynchronously method and trying to enumerate through it using a foreach that is not awaited causes a compilation error. Getting the enumerator and running MoveNext synchronously also doesn’t seem to be an option since that method returns ValueTask which doesn’t feature Wait methods and I need to capture the result of the task to know when to stop iterating.

So is it possible to force my async enomerator method synchronously and get the result as IEnumerable, and if so, how?

Solution

You could use the ToEnumerable extension method from the System.Linq.Async package. The signature of this method is:

public static IEnumerable<TSource> ToEnumerable<TSource>(
    this IAsyncEnumerable<TSource> source)

…and you could use it like this:

IEnumerable<Foo> GetItems() => GetItemsAsync().ToEnumerable();

Update: an extension method ToBlockingEnumerable with identical functionality might be included in the next version of the .NET platform (.NET 7). Related GitHub issue: Add an IAsyncEnumerable.ToEnumerable extension method.

Answered By – Theodor Zoulias

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More