Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I yield IAsyncEnumerable values as a list of Tasks complete? [duplicate]

Lets say I have a List that has 10 Tasks that each call a rest API. I'd like to run the tasks in a method that returns an IAsyncEnumerable that yields as each call is returned. I don't know what order the calls will return in.

I've looked into IAsyncEnumerable and I'm not convinced it can do this. It seems to await each Task in turn and yield the result. I want to fire all 10 Tasks at once and yield in whatever order they come back in.

It's an interesting problem I think.

like image 609
FeeFiFoFum Avatar asked Nov 28 '25 04:11

FeeFiFoFum


1 Answers

I quickly fiddled a naive approach:

public static async IAsyncEnumerable<Task<T>> WhenEach<T>(IEnumerable<Task<T>> tasks)
{
    var taskList = new List<Task<T>>(tasks);
    while( taskList.Any() )
    {
        var task = await Task.WhenAny(taskList);
        taskList.Remove(task);
        yield return task;
    }
}

It may not be Production-Ready and have some quirks but as a platform to start from, it should be enough.

like image 77
Fildor Avatar answered Nov 29 '25 18:11

Fildor