IAsyncEnumerable 的传递?

Ric*_*unt 6 c# c#-8.0 iasyncenumerable

我想知道是否有一种方法可以编写一个函数来“通过”一个 IAsyncEnumerable ......也就是说,该函数将调用另一个 IAsyncEnumerable 函数并产生所有结果而无需编写 aforeach来做到这一点?

我发现自己经常写这个代码模式。下面是一个例子:

async IAsyncEnumerable<string> MyStringEnumerator();

async IAsyncEnumerable<string> MyFunction()
{
   // ...do some code...

   // Return all elements of the whole stream from the enumerator
   await foreach(var s in MyStringEnumerator())
   {
      yield return s;
   }
}
Run Code Online (Sandbox Code Playgroud)

无论出于何种原因(由于分层设计),我的函数MyFunction都想调用,MyStringEnumerator但随后无需干预即可生成所有内容。我必须继续编写这些foreach循环才能做到这一点。如果是,IEnumerable我会返回IEnumerable. 如果是 C++,我可以写一个宏来做到这一点。

什么是最佳实践?

Ste*_*ary 7

如果它是一个 IEnumerable,我会返回 IEnumerable。

好吧,你可以做同样的事情IAsyncEnumerable(注意async被删除了):

IAsyncEnumerable<string> MyFunction()
{
 // ...do some code...

 // Return all elements of the whole stream from the enumerator
 return MyStringEnumerator();
}
Run Code Online (Sandbox Code Playgroud)

然而,这里有一个重要的语义考虑。当调用一个枚举的方法,所述...do some code...将被执行立即,和当枚举枚举。

// (calling code)
var enumerator = MyFunction(); // `...do some code...` is executed here
...
await foreach (var s in enumerator) // it's not executed here when getting the first `s`
  ...
Run Code Online (Sandbox Code Playgroud)

对于同步和异步可枚举项都是如此。

如果你想...do some code...在枚举器被枚举时被执行,那么你需要使用foreach/yield循环来获取延迟执行语义:

async IAsyncEnumerable<string> MyFunction()
{
 // ...do some code...

 // Return all elements of the whole stream from the enumerator
 await foreach(var s in MyStringEnumerator())
   yield return s;
}
Run Code Online (Sandbox Code Playgroud)

如果您也希望使用同步可枚举的延迟执行语义,则必须在同步世界中使用相同的模式:

IEnumerable<string> ImmediateExecution()
{
 // ...do some code...

 // Return all elements of the whole stream from the enumerator
 return MyStringEnumerator();
}

IEnumerable<string> DeferredExecution()
{
 // ...do some code...

 // Return all elements of the whole stream from the enumerator
 foreach(var s in MyStringEnumerator())
   yield return s;
}
Run Code Online (Sandbox Code Playgroud)