Multiple async/await chaining

前端 未结 3 2073
离开以前
离开以前 2021-01-06 22:50

How to make multiple async/await chaining in C#? For example, start few HTTP requests and then do not wait all of them, but start new request after each completed?<

相关标签:
3条回答
  • 2021-01-06 23:29

    If you want to perform some async action on a collection of items with a limited degree of parallelism, then probably the simplest way is to use ActionBlock from TPL Dataflow, since it supports async delegates (unlike most other parallel constructs in TPL, like Parallel.ForEach()).

    var block = new ActionBlock<string>(
        url => DownloadAsync(url),
        new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = few });
    
    foreach (var url in urls)
        block.Post(url);
    
    block.Complete();
    await block.Completion;
    
    0 讨论(0)
  • 2021-01-06 23:34

    The easiest way to do this is to write an async method:

    async Task DownloadAndFollowupAsync(...)
    {
      await DownloadAsync();
      await FollowupAsync();
    }
    

    Which you can then use with await Task.WhenAll:

    await Task.WhenAll(DownloadAndFollowupAsync(...),
        DownloadAndFollowupAsync(...));
    
    0 讨论(0)
  • 2021-01-06 23:41

    You can use the ContinueWith extension method of Tasks for this purpose or the extension that takes a Func and is used to return results.

    0 讨论(0)
提交回复
热议问题