How to use C#8 IAsyncEnumerable<T> to async-enumerate tasks run in parallel

i cant codez picture i cant codez · Jun 9, 2019 · Viewed 6.9k times · Source

If possible I want to create an async-enumerator for tasks launched in parallel. So first to complete is first element of the enumeration, second to finish is second element of the enumeration, etc.

public static async IAsyncEnumerable<T> ParallelEnumerateAsync(this IEnumerable<Task<T>> coldAsyncTasks)
{
    // ... 
}

I bet there is a way using ContinueWith and a Queue<T>, but I don't completely trust myself to implement it.

Answer

Paulo Morgado picture Paulo Morgado · Jun 9, 2019

Is this what you're looking for?

public static async IAsyncEnumerable<T> ParallelEnumerateAsync<T>(
    this IEnumerable<Task<T>> tasks)
{
    var remaining = new List<Task<T>>(tasks);

    while (remaining.Count != 0)
    {
        var task = await Task.WhenAny(remaining);
        remaining.Remove(task);
        yield return (await task);
    }
}