await Task.WhenAll() vs Task.WhenAll().Wait()

两盒软妹~` 提交于 2019-11-29 05:46:33

问题


I have a method that produces an array of tasks (See my previous post about threading) and at the end of this method I have the following options:

await Task.WhenAll(tasks); // done in a method marked with async
Task.WhenAll(tasks).Wait(); // done in any type of method
Task.WaitAll(tasks);

Basically I am wanting to know what the difference between the two whenalls are as the first one doesn't seem to wait until tasks are completed where as the second one does, but I'm not wanting to use the second one if it's not asynchronus.

I have included the third option as I understand that this will lock the current thread until all the tasks have completed processing (seemingly synchronously instead of asynchronus) - please correct me if I am wrong about this one

Example function with await:

public async void RunSearchAsync()
{
    _tasks = new List<Task>();
    Task<List<SearchResult>> products = SearchProductsAsync(CoreCache.AllProducts);
    Task<List<SearchResult>> brochures = SearchProductsAsync(CoreCache.AllBrochures);

    _tasks.Add(products);
    _tasks.Add(brochures);

    await Task.WhenAll(_tasks.ToArray());
    //code here hit before all _tasks completed but if I take off the async and change the above line to:

    // Task.WhenAll(_tasks.ToArray()).Wait();
    // code here hit after _tasks are completed
 }

回答1:


await will return to the caller, and resume method execution when the awaited task completes.

WhenAll will create a task **When All* all the tasks are complete.

WaitAll will block the creation thread (main thread) until all the tasks are complete.



来源:https://stackoverflow.com/questions/22966578/await-task-whenall-vs-task-whenall-wait

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!