我有一个 MVC 应用程序。我有这样的情况——我需要从多个 API 获取数据。
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");
}
}
我觉得因为对 webApi 的每次调用都在等待,所以它没有给我任何好处。因为无论如何,在我们继续下一次调用之前,我们将不得不等待数据到来。例如,第一次调用必须等到它返回 response1 等等。如果我错了,请纠正我。
有什么方法可以并行执行这 4 个语句,因为它们中的任何一个都没有依赖关系,并且我是否可以在将模型传递给 View 之前最终将 await 放在底部?
是否有任何方法可以在不冒将不完整/部分数据传递给 View 并从这些 Web API 调用并行获取数据的风险的情况下做到这一点?
请您参考如下方法:
Is there any way i can execute these 4 statements in parallel
是的,它叫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.
}
这样您就可以同时执行 4 个任务并等待它们完成。一旦他们都完成接收请求,该方法将继续执行。
