Concurrent calls C# with Example



Concurrent calls C# with Example

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 tasks = new List(); 
while (something) { 
// do stuff 
Task someAsyncTask = someAsyncMethod(); 
tasks.Add(someAsyncTask); 
} 
await Task.WhenAll(tasks); 
To get results from a task after awaiting multiple tasks with Task.WhenAll, simply await the task again. Since the 
task is already completed it will just return the result back 
var task1 = SomeOpAsync(); 
var task2 = SomeOtherOpAsync(); 
 

await Task.WhenAll(task1, task2); 
var result = await task2; 
Also, the Task.WhenAny can be used to execute multiple tasks in parallel, like the Task.WhenAll above, with the 
difference that this method will complete when any of the supplied tasks will be completed. 
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. 

0 Comment's

Comment Form

Submit Comment