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.

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.

Jaganathan Bantheswaran

Hi everyone,This is jagan . Working as Software Engineer for SDL International. Bengaluru, India.Thanks,Be simple & sample - Jaganhttp://www.iamtechmad.com,

Personal Blog: http://jagan-bhathri.com
COMMENT USING

PREMIUM SPONSORS

Hire Mobile & Web Developer on demand. 100% satisfaction. Try for 1 week or Money Back. Local and remote developers available all over USA.

Latest Blogs