首页 > 解决方案 > 如何返回异步 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#

解决方案


在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 );
}

推荐阅读