Is it possible to “await yield return DoSomethingAsync()”

前端 未结 9 962
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 14:08

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:

asyn         


        
9条回答
  •  盖世英雄少女心
    2020-11-27 14:52

    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> DownLoadAllUrls(string[] urls)
    {
        return Task.WhenAll(from url in urls select DownloadHtmlAsync(url));
    }
    

提交回复
热议问题