.Net / C# Waiting for Multiple Async Responses

While writing programs we can often come across situations when we must wait for results from different asynchronous calls. This is required when the processing is dependent upon multiple responses from external medium like web services. Lets look at the mentioned below 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 above code , we are executing asynchronous calls to different servers. Suppose we must wait for output from all of them before we can proceed ahead we can use the statement “WhenAll”. This will ensure that the compiler will wait for responses from all the three asynchronous calls before the processing can move ahead.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s