Blog

How to Execute Async Methods Parallelly

By Jaganathan Bantheswaran Oct 14 2013
In this blog, we are going to discuss how to execute async methods parallelly.
    • Like
    • Love It
    • Awesome
    • Interesting
    • It's Okay
    • Thumbs Down
  • 3k
  • 0

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.