Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between WaitAll and WhenAll? [duplicate]

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?

like image 719
Álvaro García Avatar asked Oct 25 '14 16:10

Álvaro García


People also ask

What is the difference between WhenAll and 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.

What is the difference between task WaitAll and task WhenAll?

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.

Can you tell difference between task WhenAll and task WhenAny?

WhenAll returns control after all tasks are completed, while WhenAny returns control as soon as a single task is completed.

What is the use of task WhenAll?

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.


2 Answers

MSDN does a good job of explaining this. The difference is pretty unambiguous.

Task.WhenAll:

Creates a task that will complete when all of the supplied tasks have completed.

Task.WaitAll:

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.

like image 72
Ant P Avatar answered Oct 04 '22 06:10

Ant P


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

like image 41
Darren Kopp Avatar answered Oct 04 '22 07:10

Darren Kopp