Sahil Sharma
Sahil Sharma

Reputation: 4217

MVC4 async await has any benefit if we only have series of calls with no independent work?

I have a MVC application.I have situation like this-- I need to bring data from multiple APIs.

public class MVCController : Controller
{
    // MVC controller calling WebApis to bring data.
    public async Task<ActionResult> Index()
    {
        var response1 = await client.GetAsync("webapi/WebApiController1/Method1");
        var response2 = await client.GetAsync("webapi/WebApiController2/Method2");
        var response3 = await client.GetAsync("webapi/WebApiController3/Method3");
        var response4 = await client.GetAsync("webapi/WebApiController4/Method4");
    }
}

I feel since every call to the webApi has await, it is not giving me any benefit. Since anyhow we will have to wait for data to come before we proceed with the next call. For example 1st call will have to wait until it gets back the response1 and so on. Please correct me if i am wrong.

Is there any way i can execute these 4 statements in parallel since any of these do not have dependency and if i can finally put await at bottom before passing the model to the view?

If there is any approach to do that without risking of passing incomplete/partial data to the View and getting the data from these Web API calls in parallel?

Upvotes: 1

Views: 65

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

Is there any way i can execute these 4 statements in parallel

Yes, it's called Task.WhenAll:

public async Task<ActionResult> Index()
{
    var response1 = client.GetAsync("webapi/WebApiController1/Method1");
    var response2 = client.GetAsync("webapi/WebApiController2/Method2");
    var response3 = client.GetAsync("webapi/WebApiController3/Method3");
    var response4 = client.GetAsync("webapi/WebApiController4/Method4");

    await Task.WhenAll(response1, response2, response3, response4);
    // You will reach this line once all requests finish execution.
}

This way you concurrently execute 4 tasks and wait for them to complete. The method will continue execution once they all finished receiving the requests.

Upvotes: 4

Related Questions