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?<
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;
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(...));
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.