本文介绍了是否有可能"等待产量回报DoSomethingAsync()"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是正规迭代器块(即收益回报率)与异步和等待不相容?

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".

下面是真正的编程code在我的项目

Here is the real programming code in my project

这是非常有用的,当我有一个列出任务,该任务可下载HTML从URL
我用的是语法收益回报等待任务,结果是我想要的IEnumerable&LT;富&GT; 。我不想写这code:

This is very useful when I have an List Task,that task can be download HTML from a URLand 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;
}

但似乎我不得不这样做。

But it seems that I have to.

感谢您的帮助。

推荐答案

你所描述可以用 Task.WhenAll 方法来完成。注意code是如何变成一个简单的一行。什么情况是,每个单独的URL开始下载,然后 WhenAll 用于合并这些操作成一个单一的工作可以是期待已久的。

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

这篇关于是否有可能&QUOT;等待产量回报DoSomethingAsync()&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 05:05