In termini di prestazioni, questi 2 metodi eseguiranno GetAllWidgets()
e GetAllFoos()
in parallelo?più attende vs Task.WaitAll - equivalente?
C'è qualche motivo per usare l'uno sull'altro? Sembra che ci sia molto successo dietro le quinte con il compilatore, quindi non lo trovo chiaro.
============= MethodA: L'utilizzo di più attende ======================
public async Task<IHttpActionResult> MethodA()
{
var customer = new Customer();
customer.Widgets = await _widgetService.GetAllWidgets();
customer.Foos = await _fooService.GetAllFoos();
return Ok(customer);
}
=============== MethodB: Usando 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);
}
=======================
Nel primo esempio i due metodi verranno chiamati in sequenza e nel secondo verranno eseguiti in parallelo, quindi non sono equivalenti. Inoltre, nel tuo secondo metodo stai bloccando mentre esegui le attività. –
MethodA eseguirà '_fooService.GetAllFoos()' solo quando '_widgetService.GetAllWidgets()' ha finito, methodB lo eseguirà quando l'attività incompleta da '_fooService.GetAllFoos()' ritorna. –