[英]Task C#, list of Tast<T> and Task.Wait()
I have simple code and I would know answer: 我有简单的代码,我会知道答案:
List<Task<int>> list = new List<Task<int>>;
for(int i=0;i<10;i++)
{
list.Add(new Task<int>((j) => return (int)j%2, i);
}
list.Foreach(t => t.Start());
And now I want to wait for all Tasks
, well it's good idea?: 现在我要等待所有Tasks
,这是个好主意吗?:
Task.WaitAll(list.ToArray());
PS: PS:
describtion about WaitAll
: 关于WaitAll
:
public static void WaitAll(params Task[] tasks)
Yes, that's exactly what Task.WaitAll
is for. 是的,这正是Task.WaitAll
的用途。
But if you know how many tasks you're going to have before creating them, you should stick to Task[]
instead of List<Task>
from the very beginning: 但是,如果在创建任务之前知道要完成多少任务,则应从一开始就坚持使用Task[]
而不是List<Task>
:
var tasks = new Task[10];
for(int i=0;i<10;i++)
{
var task = new Task<int>(x => return x % 2, i);
tasks[i] = task;
task.Start();
}
Task.WaitAll(tasks);
This allows you to skip moving from List<T>
to T[]
array back and forth. 这使您可以跳过从List<T>
到T[]
数组的来回移动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.