是否可以“等待收益返回 DoSomethingAsync()"? [英] Is it possible to "await yield return DoSomethingAsync()"
问题描述
常规迭代器块(即yield return")是否与async"和await"不兼容?
Are regular iterator blocks (i.e. "yield return") incompatible with "async" and "await"?
这很好地说明了我要做什么:
This gives a good idea of what I'm trying to do:
async Task<IEnumerable<Foo>> Method(String [] Strs)
{
// I want to compose the single result to the final result, so I use the SelectMany
var finalResult = UrlStrings.SelectMany(link => //i have an Urlstring Collection
await UrlString.DownLoadHtmlAsync() //download single result; DownLoadHtmlAsync method will Download the url's html code
);
return finalResult;
}
但是,我收到一个编译器错误,指出无法从资源加载消息字符串".
However, I get a compiler error citing "unable to load message string from resources".
这是另一个尝试:
async Task<IEnumerable<Foo>> Method(String [] Strs)
{
foreach(var str in strs)
{
yield return await DoSomethingAsync( str)
}
}
但是,编译器再次返回错误:无法从资源加载消息字符串".
But again, the compiler returns an error: "unable to load message string from resources".
这是我项目中真正的编程代码
Here is the real programming code in my project
当我有一个列表任务时,这非常有用,该任务可以从 URL 下载 HTML我使用语法yield return await task",结果是我想要IEnumerable
.我不想写这段代码:
This is very useful when I have an List Task,that task can be download HTML from a URL
and I use the syntax "yield return await task", the result is I want IEnumerable<Foo>
. I don't want write this code:
async Task<IEnumerable<String>> DownLoadAllURL(String [] Strs)
{
List<Foo> htmls= new ...
foreach(var str in strs)
{
var html= await DownLoadHtmlAsync( str)
htmls.Add(item)
}
return htmls;
}
但似乎我必须这样做.
感谢您的帮助.
推荐答案
您所描述的可以使用 Task.WhenAll
方法来完成.请注意代码如何变成简单的单行代码.发生的情况是每个单独的 url 开始下载,然后使用 WhenAll
将这些操作组合成一个可以等待的 Task
.
What you are describing can be accomplished with the Task.WhenAll
method. Notice how the code turns into a simple one-liner. What happens is that each individual url begins downloading and then WhenAll
is used combine those operations into a single Task
which can be awaited.
Task<IEnumerable<string>> DownLoadAllUrls(string[] urls)
{
return Task.WhenAll(from url in urls select DownloadHtmlAsync(url));
}
这篇关于是否可以“等待收益返回 DoSomethingAsync()"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!