等待Task.WhenAll()与Task.WhenAll().Wait() [英] await Task.WhenAll() vs Task.WhenAll().Wait()
问题描述
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);
基本上,我想知道两个whenall
之间的区别是,第一个似乎并没有等到任务完成时才开始,而第二个却在做,但是我不想使用如果不是异步的话,第二个.
Basically I am wanting to know what the difference between the two whenall
s 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
等待功能的示例:
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
}
推荐答案
await
将返回到调用方,并在等待的任务完成时恢复方法执行.
await
will return to the caller, and resume method execution when the awaited task completes.
WhenAll
将创建一个任务**当全部"完成时,所有任务.
WhenAll
will create a task **When All* all the tasks are complete.
WaitAll
将阻塞创建线程(主线程),直到所有任务完成.
WaitAll
will block the creation thread (main thread) until all the tasks are complete.
这篇关于等待Task.WhenAll()与Task.WhenAll().Wait()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!