Using the await statement for parallel asynchronous calls

While writing programs, we often come across situations in which we must wait for results from different asynchronous calls. This is required when the processing is dependent upon multiple responses from an external medium, such as web services. Let's look at the following code example:

public async Task ExecuteMultipleRequestsInParallel()
{
HttpClient client = new HttpClient();
Task google = client.GetStringAsync("http://www.google.com");
Task bing = client.GetStringAsync("http://www.bing.com");
Task yahoo = client.GetStringAsync("http://yahoo.com/");
await Task.WhenAll(google, bing, yahoo);
}

In the preceding code, we are executing asynchronous calls to different servers. Suppose we have to wait for the output from all of them before we can proceed; we can use the WhenAll statement. The WhenAll statement will ensure that the execution waits for responses from all three asynchronous calls before the processing can move ahead.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.73.127