就性能而言,这两种方法会同时运行GetAllWidgets()
和GetAllFoos()
吗?
选择一种方法比另一种更有理由吗?编译器在幕后进行了很多操作,所以我不是很清楚。
============= 方法A:使用多个awaits ======================
public async Task<IHttpActionResult> MethodA()
{
var customer = new Customer();
customer.Widgets = await _widgetService.GetAllWidgets();
customer.Foos = await _fooService.GetAllFoos();
return Ok(customer);
}
=============== 方法B:使用Task.WaitAll =====================
public async Task<IHttpActionResult> MethodB()
{
var customer = new Customer();
var getAllWidgetsTask = _widgetService.GetAllWidgets();
var getAllFoosTask = _fooService.GetAllFos();
Task.WaitAll(new List[] {getAllWidgetsTask, getAllFoosTask});
customer.Widgets = getAllWidgetsTask.Result;
customer.Foos = getAllFoosTask.Result;
return Ok(customer);
}
抱歉,我只能使用英文回答您的问题。
_widgetService.GetAllWidgets()
完成后,MethodA 将执行_fooService.GetAllFoos()
。而 methodB 则会在_fooService.GetAllFoos()
的未完成任务返回时执行它。 - shay__