Dark Hydra
Dark Hydra

Reputation: 275

Multiple async/await chaining

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?

Upvotes: 3

Views: 6107

Answers (3)

svick
svick

Reputation: 244777

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;

Upvotes: 2

Stephen Cleary
Stephen Cleary

Reputation: 456497

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

Upvotes: 14

Savvas Kleanthous
Savvas Kleanthous

Reputation: 2745

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.

Upvotes: 1

Related Questions