神奇的Task.WaitALl
Task.WaitAll的参数是Task列表,参数取值不同 运行的结果也不同
1.下边代码的运行结果是先打印"wait all"
for (int i = 0; i < 100; i++) { taskList.Add(new Task(async () => { await Task.Delay(5000); Console.WriteLine(Thread.CurrentThread.ManagedThreadId); })); } taskList.ForEach(p=>p.Start()); await Task.Delay(1000); Task.WaitAll(taskList.ToArray()); Console.WriteLine("wait all");
2.下边的结果是永远等待
for (int i = 0; i < 100; i++) { taskList.Add(new Task(async () => { await Task.Delay(5000); Console.WriteLine(Thread.CurrentThread.ManagedThreadId); })); } //taskList.ForEach(p=>p.Start()); await Task.Delay(1000); Task.WaitAll(taskList.ToArray()); Console.WriteLine("wait all");
3.下边的结果是先打印"wait all"
var taskList = new List<Task>(); for (int i = 0; i < 100; i++) { var t1 =Task.Factory.StartNew(async ()=> { await Task.Delay(5000); Console.WriteLine(Thread.CurrentThread.ManagedThreadId); }); taskList.Add(t1); } Task.WaitAll(taskList.ToArray()); Console.WriteLine("wait all");
4.下边的结果是最后打印"wait all"
var taskList = new List<Task>(); for (int i = 0; i < 100; i++) { var t1 =Task.Start(async ()=> { await Task.Delay(5000); Console.WriteLine(Thread.CurrentThread.ManagedThreadId); }); taskList.Add(t1); } Task.WaitAll(taskList.ToArray()); Console.WriteLine("wait all");