我想知道是否有一种方法,我可以写一个函数“通过”一个IAsyncEnumerable.也就是说,该函数将调用另一个IAsyncEnumerable函数并生成所有结果,而不必编写foreach来完成它?
我发现自己经常编写这种代码模式。下面是一个例子:
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;
}
}无论出于什么原因(由于分层设计),我的函数MyFunction都想调用MyStringEnumerator,但是不需要干预就可以生成所有东西。我必须不断地编写这些foreach循环来完成它。如果是IEnumerable,我会返回IEnumerable。如果是C++,我可以编写一个宏来完成它。
什么是最佳实践?
发布于 2020-01-23 14:04:26
,如果是IEnumerable,我会返回IEnumerable。
好吧,您可以对IAsyncEnumerable做同样的事情(注意,async被删除了):
IAsyncEnumerable<string> MyFunction()
{
// ...do some code...
// Return all elements of the whole stream from the enumerator
return MyStringEnumerator();
}然而,这里有一个重要的语义考虑。当调用枚举数方法时,将立即执行...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`
...同步和异步枚举都是如此。
如果希望枚举器枚举时执行...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;
}如果您也希望使用同步可枚举的延迟执行语义,则必须在同步世界中使用相同的模式:
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;
}发布于 2020-03-05 09:48:33
从调用方法返回Task<IAsyncEnumerable<Obj>>似乎有效
async IAsyncEnumerable<string> MyStringEnumerator();
async Task<IAsyncEnumerable<string>> MyFunction()
{
await Something();
return MyStringEnumerator();
}然后,您需要等待MyFunction()。因此,要在异步预测中使用
await foreach (string s in await MyFunction()) {}https://stackoverflow.com/questions/59876417
复制相似问题