如何返回异步IEnumerable <string>?

时间:2019-05-07 12:25:06

标签: c#

我有以下方法:

public async IEnumerable<string> GetListDriversAsync()
{
   var drives = await graphClient.Drive.Root.Children.Request().GetAsync();
        foreach (var d in drives)
            yield return d.ToString(); 
}

但是编译器错误说:

  

“异步的返回类型必须为空,任务或任务<T>

方法异步时如何返回IEnumerable?

2 个答案:

答案 0 :(得分:2)

尝试一下:

public async Task<IEnumerable<string>> GetListDriversAsync()
{
    var drives = await graphClient.Drive.Root.Children.Request().GetAsync();

    IEnumerable<string> GetListDrivers()
    {
        foreach (var d in drives)
            yield return d.ToString();
    }

    return GetListDrivers();
}

答案 1 :(得分:0)

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