Updated on Kisan Patel
You can run more than one async calls in parallel and save each result as a Task. You can then await each Task using the Task.WhenAll method.
The Task.WhenAll
method takes either an array of Task objects or an IEnumerable of Task as a parameter and will return an array when all the Tasks have completed.
For Example, here we will use WebClient
to download three web pages in parallel using async method.
class Program { static void Main(string[] args) { Task<string[]> t = CallThreeServicesAsync(); t.Wait(); var result = t.Result; Console.ReadKey(); } static async Task<string[]> CallThreeServicesAsync() { Task<string> t1, t2, t3; using (WebClient webClient = new WebClient()) { Uri uri1 = new Uri(string.Format("http://google.co.uk", 1)); t1 = webClient.DownloadStringTaskAsync(uri1); } using (WebClient webClient = new WebClient()) { Uri uri2 = new Uri(string.Format("http://google.co.in", 2)); t2 = webClient.DownloadStringTaskAsync(uri2); } using (WebClient webClient = new WebClient()) { Uri uri3 = new Uri(string.Format("http://google.com", 3)); t3 = webClient.DownloadStringTaskAsync(uri3); } string[] results = await Task.WhenAll(new Task<string>[] { t1, t2, t3 }); return results; } }
For this example, we make three web service calls asynchronously using the WebClient.DownloadStringTaskAsync
method. This method takes a URL as a parameter and returns a Task.