How to Execute Async Methods Parallelly

When you have many asynchronous methods which has to be executed parallelly, we need to follow as shown below.

public async Task Index()

{

  var tasks = new [] {

  Task.Run(() => DoSomethingAsync(10000)),

  Task.Run(() => DoSomethingAsync(1000)),

  Task.Run(() => DoSomethingAsync(10000)),

};

var results = await Task.WhenAll(tasks);

return View(results.First());

}

In this above code, we have array of tasks which will be executing the below asynchronous method. The WhenAll() method will be completed when all the tasks are done.
 

[NonAction]

public async Task DoSomethingAsync(int milliseconds)

{

await Task.Delay(milliseconds);

return milliseconds;

}

The DoSomethingAsync() method will be delayed by the given milliseconds and returns the milliseconds.

Ebook Download
View all
Learn
View all