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

前端 未结 9 939
佛祖请我去吃肉
佛祖请我去吃肉 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:39

    I know that I'm too late with the answer, but here is another simple solution that can be achieved with this library:
    GitHub: https://github.com/tyrotoxin/AsyncEnumerable
    NuGet.org: https://www.nuget.org/packages/AsyncEnumerator/
    It's much simpler than Rx.

    using System.Collections.Async;
    
    static IAsyncEnumerable ProduceItems(string[] urls)
    {
      return new AsyncEnumerable(async yield => {
        foreach (var url in urls) {
          var html = await UrlString.DownLoadHtmlAsync(url);
          await yield.ReturnAsync(html);
        }
      });
    }
    
    static async Task ConsumeItemsAsync(string[] urls)
    {
      await ProduceItems(urls).ForEachAsync(async html => {
        await Console.Out.WriteLineAsync(html);
      });
    }
    

提交回复
热议问题