21

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?

Shaharyar
  • 12,254
  • 4
  • 46
  • 66
Álvaro García
  • 18,114
  • 30
  • 102
  • 193
  • 1
    You can `await` Task.WhenAll without blocking the calling thread. – L.B Oct 25 '14 at 16:40
  • Exception handling is different as well, please see http://stackoverflow.com/questions/6123406/waitall-vs-whenall – tymtam Nov 20 '16 at 12:46

2 Answers2

27

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.

Ant P
  • 24,820
  • 5
  • 68
  • 105
18

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

Darren Kopp
  • 76,581
  • 9
  • 79
  • 93