I have this code:
List<ComponentesClasificaciones> misClasificaciones = new List<ComponentesClasificaciones>();
Task tskClasificaciones = Task.Run(() =>
{
misClasificaciones = VariablesGlobales.Repositorio.buscarComponentesClasificacionesTodosAsync().Result;
});
Task.WhenAll(tskClasificaciones);
List<ComponentesClasificaciones> misVClasificacionesParaEstructuras = new List<ComponentesClasificaciones>(misClasificaciones);
If I use Task.WhenAll
, misClasificaciones
does not have any element but when I use awit all I get all the elements that I request to the database.
When to use WhenAll
and when to use WaitAll
?
WaitAll blocks the current thread until everything has completed. Task. WhenAll returns a task which represents the action of waiting until everything has completed.
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.
public static Task WhenAll (params Task[] tasks); Task. WhenAll creates a task that will complete when all of the supplied tasks have been completed. It's pretty straightforward what this method does, it simply receives a list of Tasks and returns a Task when all of the received Tasks completes.
MSDN does a good job of explaining this. The difference is pretty unambiguous.
Creates a task that will complete when all of the supplied tasks have completed.
Waits for all of the provided Task objects to complete execution.
So, essentially, WhenAll
gives you a task that isn't done until all of the tasks you give it are done (and allows program execution to continue immediately), whereas WaitAll
just blocks and waits for all of the tasks you pass to finish.
WhenAll
returns a task that you can ContinueWith
once all the specified tasks are complete. You should be doing
Task.WhenAll(tskClasificaciones).ContinueWith(t => {
// code here
});
Basically, use WaitAll
when you want to synchronously get the results, use WhenAll
when you want to start a new asynchronous task to start some more processing
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