如何使用C#8 IAsyncEnumerable< T>异步枚举并行运行的任务 [英] How to use C#8 IAsyncEnumerable<T> to async-enumerate tasks run in parallel

查看:330
本文介绍了如何使用C#8 IAsyncEnumerable< T>异步枚举并行运行的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果可能的话,我想为并行启动的任务创建一个异步枚举器.因此,首先要完成的是枚举的第一个元素,其次要完成的是枚举的第二个元素,依此类推.

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)
{
    // ... 
}

我敢肯定有一种使用ContinueWithQueue<T>的方法,但是我并不完全相信自己能够实现它.

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

推荐答案

这是您要寻找的吗?

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);
    }
}

这篇关于如何使用C#8 IAsyncEnumerable&lt; T&gt;异步枚举并行运行的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆