简体   繁体   中英

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?:

Task.WaitAll(list.ToArray());

PS:

describtion about WaitAll :

public static void WaitAll(params Task[] tasks)

Yes, that's exactly what Task.WaitAll is for.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM