Method(String [] Strs)-6ren">
gpt4 book ai didi

c# - 有没有可能到 "await yield return DoSomethingAsync()"

转载 作者:IT王子 更新时间:2023-10-29 03:36:45 25 4
gpt4 key购买 nike

常规迭代器 block (即“yield return”)是否与“async”和“await”不兼容?

这很好地说明了我要做什么:

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

但是,我收到一个编译器错误,指出“无法从资源中加载消息字符串”。

这是另一种尝试:

async Task<IEnumerable<Foo>> Method(String [] Strs)
{
foreach(var str in strs)
{
yield return await DoSomethingAsync( str)
}
}

但是,编译器再次返回错误:“无法从资源加载消息字符串”。


这是我项目中真正的编程代码

这在我有一个列表任务时非常有用,该任务可以从 URL 下载 HTML我使用语法“yield return await task”,结果是我想要 IEnumerable<Foo> .我不想写这段代码:

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 中。

Task<IEnumerable<string>> DownLoadAllUrls(string[] urls)
{
return Task.WhenAll(from url in urls select DownloadHtmlAsync(url));
}

关于c# - 有没有可能到 "await yield return DoSomethingAsync()",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5061761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com