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

后端 未结 5 1853
孤独总比滥情好
孤独总比滥情好 2021-02-09 15:00

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

5条回答
  •  野的像风
    2021-02-09 15:14

    Is this what you're looking for?

    public static async IAsyncEnumerable ParallelEnumerateAsync(
        this IEnumerable> tasks)
    {
        var remaining = new List>(tasks);
    
        while (remaining.Count != 0)
        {
            var task = await Task.WhenAny(remaining);
            remaining.Remove(task);
            yield return (await task);
        }
    }
    

提交回复
热议问题