What is the difference between WaitAll and WhenAll

2019-02-09 23:34发布

This question already has an answer here:

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?

2条回答
beautiful°
2楼-- · 2019-02-09 23:39

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.

查看更多
时光不老,我们不散
3楼-- · 2019-02-09 23:51

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

查看更多
登录 后发表回答