首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过IAsyncEnumerable?

通过IAsyncEnumerable?
EN

Stack Overflow用户
提问于 2020-01-23 10:31:09
回答 2查看 3.6K关注 0票数 7

我想知道是否有一种方法,我可以写一个函数“通过”一个IAsyncEnumerable.也就是说,该函数将调用另一个IAsyncEnumerable函数并生成所有结果,而不必编写foreach来完成它?

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

代码语言:javascript
复制
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++,我可以编写一个宏来完成它。

什么是最佳实践?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-01-23 14:04:26

,如果是IEnumerable,我会返回IEnumerable。

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

代码语言:javascript
复制
IAsyncEnumerable<string> MyFunction()
{
 // ...do some code...

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

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

代码语言:javascript
复制
// (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循环来获得延迟执行语义:

代码语言:javascript
复制
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;
}

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

代码语言:javascript
复制
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;
}
票数 12
EN

Stack Overflow用户

发布于 2020-03-05 09:48:33

从调用方法返回Task<IAsyncEnumerable<Obj>>似乎有效

代码语言:javascript
复制
async IAsyncEnumerable<string> MyStringEnumerator();

async Task<IAsyncEnumerable<string>> MyFunction()
{
    await Something();

    return MyStringEnumerator();
}

然后,您需要等待MyFunction()。因此,要在异步预测中使用

代码语言:javascript
复制
await foreach (string s in await MyFunction()) {}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59876417

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档