[英]How to return async IEnumerable<string>?
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>
" “异步的返回类型必须为空,Task或Task<T>
”
How do I return IEnumerable when the method is async? 方法异步时如何返回IEnumerable?
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();
}
An alternative way is possible in C# 8 . 在C#8中,可以使用另一种方法。 It uses IAsyncEnumerable . 它使用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 );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.