multithreading await Task.WhenAll() 与 Task.WhenAll().Wait()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22966578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 01:25:12  来源:igfitidea点击:

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

multithreadingasync-awaitc#-5.0

提问by Pete

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.

基本上我想知道这两个whenalls之间的区别是什么,因为第一个似乎不像第二个那样等到任务完成,但是如果它不是异步的,我不想使用第二个.

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
 }

回答by T McKeown

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

await将返回给调用者,并在等待的任务完成时恢复方法执行。

WhenAllwill createa task **When All* all the tasks are complete.

WhenAll创建一个任务**当所有*所有任务都完成时。

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

WaitAll将阻塞创建线程(主线程),直到所有任务完成。