In terms of performance, will these 2 methods run GetAllWidgets()
and GetAllFoos()
in parallel?
Is there any reason to use one over the other? There seems to be a lot happening behind the scenes with the compiler so I don't find it clear.
============= MethodA: Using multiple awaits ======================
public async Task<IHttpActionResult> MethodA() { var customer = new Customer(); customer.Widgets = await _widgetService.GetAllWidgets(); customer.Foos = await _fooService.GetAllFoos(); return Ok(customer); }
=============== MethodB: Using 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); }
=====================================
The Task. WaitAll blocks the current thread until all other tasks have completed execution. The Task. WhenAll method is used to create a task that will complete if and only if all the other tasks have completed.
WhenAll returns control after all tasks are completed, while WhenAny returns control as soon as a single task is completed.
WaitAll(Task[], TimeSpan) Waits for all of the provided cancellable Task objects to complete execution within a specified time interval. WaitAll(Task[], Int32, CancellationToken) Waits for all of the provided Task objects to complete execution within a specified number of milliseconds or until the wait is cancelled.
WhenAll(Task[])Creates a task that will complete when all of the Task objects in an array have completed.
The first option will not execute the two operations concurrently. It will execute the first and await its completion, and only then the second.
The second option will execute both concurrently but will wait for them synchronously (i.e. while blocking a thread).
You shouldn't use both options since the first completes slower than the second and the second blocks a thread without need.
You should wait for both operations asynchronously with Task.WhenAll
:
public async Task<IHttpActionResult> MethodB() { var customer = new Customer(); var getAllWidgetsTask = _widgetService.GetAllWidgets(); var getAllFoosTask = _fooService.GetAllFos(); await Task.WhenAll(getAllWidgetsTask, getAllFoosTask); customer.Widgets = await getAllWidgetsTask; customer.Foos = await getAllFoosTask; return Ok(customer); }
Note that after Task.WhenAll
completed both tasks already completed so awaiting them completes immediately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With