Concurrent calls

suggest change

It is possible to await multiple calls concurrently by first invoking the awaitable tasks and then awaiting them.

public async Task RunConcurrentTasks()
{
    var firstTask = DoSomethingAsync();
    var secondTask = DoSomethingElseAsync();
		await firstTask;
    await secondTask;
}

Alternatively, Task.WhenAll can be used to group multiple tasks into a single Task, which completes when all of its passed tasks are complete.

public async Task RunConcurrentTasks()
{
    var firstTask = DoSomethingAsync();
    var secondTask = DoSomethingElseAsync();
		await Task.WhenAll(firstTask, secondTask);
}

You can also do this inside a loop, for example:

List<Task> tasks = new List<Task>();
while (something) {
    // do stuff
    Task someAsyncTask = someAsyncMethod();
    tasks.Add(someAsyncTask);
}
await Task.WhenAll(tasks);

To get a result after Task.WhenAll, await that task again. The task is already complete, so the await returns its result.

var task1 = SomeOpAsync();
var task2 = SomeOtherOpAsync();

await Task.WhenAll(task1, task2);

var result = await task2;

Task.WhenAny waits for the same kind of already started tasks, and completes when any one of them completes.

public async Task RunConcurrentTasksWhenAny()
{
    var firstTask = TaskOperation("#firstTask executed");
    var secondTask = TaskOperation("#secondTask executed");
    var thirdTask = TaskOperation("#thirdTask executed");
    await Task.WhenAny(firstTask, secondTask, thirdTask);
}

The Task returned by RunConcurrentTasksWhenAny will complete when any of firstTask, secondTask, or thirdTask completes.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents