Can I yield IAsyncEnumerable values as a list of Tasks complete?
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 yie开发者_运维百科lds 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.
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.
精彩评论