/// <summary> /// 基于Task的多线程 /// </summary> public class Tasks { public static void TaskAction() { Console.WriteLine("********************开始当前线程为{0}", Thread.CurrentThread.ManagedThreadId); Console.WriteLine("接到一个项目"); Console.WriteLine("沟通,谈价钱"); Console.WriteLine("收去50%的费用......"); Console.WriteLine("需求分析,设计系统"); TaskFactory taskFactory = new TaskFactory(); List<Task> TaskList = new List<Task>(); Action action1 = () => StarPoj("张三"); TaskList.Add(taskFactory.StartNew(action1)); Action action2 = () => StarPoj("李四"); TaskList.Add(taskFactory.StartNew(action2)); Action action3 = () => StarPoj("王五"); TaskList.Add(taskFactory.StartNew(action3)); Action action4 = () => StarPoj("赵六"); TaskList.Add(taskFactory.StartNew(action4)); Action<Task[]> ActAll = new Action<Task[]>(t => Console.WriteLine("开发完成,进行联调,当前线程为{0}", Thread.CurrentThread.ManagedThreadId)); Task taskAll= taskFactory.ContinueWhenAll(TaskList.ToArray(), ActAll);//等待TaskList线程集合完成后再开启ActAll另一个线程 Task.WaitAny(TaskList.ToArray());//等待某一个线程完成再执行 Console.WriteLine("测试,收取20%费用"); //Task.WaitAll(TaskList.ToArray());//等待所有的线程完成 Task.WaitAll(new Task[] { taskAll });//等待taskAll该线程完成后再执行 Console.WriteLine("收钱"); Console.WriteLine("********************结束当前线程为{0}", Thread.CurrentThread.ManagedThreadId); } public static void StarPoj(string name) { Console.WriteLine("{0}开始编码,当前线程为{1}", name, Thread.CurrentThread.ManagedThreadId); } }