Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return async IEnumerable<string>?

Tags:

c#

I have the following method:

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

But compiler error says:

"The return type of an async must be void, Task or Task <T>"

How do I return IEnumerable when the method is async?

like image 491
Codey Avatar asked Jul 14 '26 05:07

Codey


2 Answers

An alternative way is possible in C# 8. It uses IAsyncEnumerable.

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

It will alter your signature a bit, which may (or may not) be an option for you.

Usage:

await foreach (var driver in foo.GetListDriversAsync())
{
    Console.WriteLine(driver );
}
like image 142
smoksnes Avatar answered Jul 15 '26 18:07

smoksnes


Try this:

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();
}
like image 35
Enigmativity Avatar answered Jul 15 '26 19:07

Enigmativity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!