c# - 如何返回异步 IEnumerable?
问题描述
我有以下方法:
public async IEnumerable<string> GetListDriversAsync()
{
var drives = await graphClient.Drive.Root.Children.Request().GetAsync();
foreach (var d in drives)
yield return d.ToString();
}
但是编译器错误说:
“异步的返回类型必须是 void、Task 或 Task
<T>
”
方法异步时如何返回 IEnumerable?
解决方案
在C# 8中可以使用另一种方法。它使用IAsyncEnumerable。
public async IAsyncEnumerable<string> GetListDriversAsync()
{
var drives = await graphClient.Drive.Root.Children.Request().GetAsync();
foreach (var d in drives)
yield return d.ToString();
}
它会稍微改变您的签名,这可能(或可能不会)是您的选择。
用法:
await foreach (var driver in foo.GetListDriversAsync())
{
Console.WriteLine(driver );
}
推荐阅读
- firebase - 通过“凭据”属性提供给 initializeApp() 的凭据实现未能获取有效的 Google OAuth2
- android - 如何在颤动中仅播放自定义声音以进行通知?
- php - 在 WHERE 子句中使用 MySQL CONCAT_WS 和另一个 WHERE 子句
- ios - 仅在 iOS 设备上提供字体文件的错误“未实现类型:7”
- javascript - 如何加快 Google ReCAPTCHA V3 页面加载速度
- javascript - javascript中if块内的变量和函数范围
- python - 安装库时 Pip 安装速度慢得离谱
- java - 当我尝试从手机上的 Android Studio 运行应用程序时,我的应用程序显示运行时异常
- python - 使用小部件修改 django 模型表单字段
- mysql - 在 MySQL 中使用 ROLLUP 时将小数列四舍五入