如何等待多个 IAsyncEnumerable

Wla*_*law 4 .net c# .net-core c#-8.0 iasyncenumerable

我们有这样的代码:

var intList = new List<int>{1,2,3};
var asyncEnumerables = intList.Select(Foo);

private async IAsyncEnumerable<int> Foo(int a)
{
  while (true)
  {
    await Task.Delay(5000);
    yield return a;
  } 
}
Run Code Online (Sandbox Code Playgroud)

我需要await foreach为每个asyncEnumerable条目开始。每次循环迭代都应该相互等待,每次迭代完成后,我需要收集每次迭代的数据并通过另一种方法对其进行处理。

我可以通过 TPL 以某种方式实现吗?否则,你不能给我一些想法吗?

Wla*_*law 5

对我Zip有用的是这个repo 中的函数(81 行)

我是这样用的

var intList = new List<int> { 1, 2, 3 };
var asyncEnumerables = intList.Select(RunAsyncIterations);
var enumerableToIterate = async_enumerable_dotnet.AsyncEnumerable.Zip(s => s, asyncEnumerables.ToArray());

await foreach (int[] enumerablesConcatenation in enumerableToIterate)
{
    Console.WriteLine(enumerablesConcatenation.Sum()); //Sum returns 6
    await Task.Delay(2000);
}

static async IAsyncEnumerable<int> RunAsyncIterations(int i)
{
    while (true)
        yield return i;
}
Run Code Online (Sandbox Code Playgroud)