1. 通过Task启动多线程
2. 解决多线程的几大应用场景
private void btnTask_Click(object sender, EventArgs e) { Console.WriteLine("************************btnTask_Click Begin*************************"); Console.WriteLine("Eleven老师接到私单项目"); Console.WriteLine("沟通需求,确认需求,谈价格"); Console.WriteLine("签合同,受50%的首期费用"); Console.WriteLine("老师筛选学员,组建团队"); Console.WriteLine("完成初步设计,系统分工"); Console.WriteLine("老师干活....."); TaskFactory factory = new TaskFactory(); //创建一个Task工厂 List<Task> tasklist = new List<Task>(); tasklist.Add(factory.StartNew( //匿名函数 delegate () { this.coding("PoPo", "WCF"); } )); tasklist.Add(factory.StartNew(() => this.coding("YoYo", "Portal"))); tasklist.Add(factory.StartNew(() => this.coding("DoDo", "Client"))); tasklist.Add(factory.StartNew(() => this.coding("WoWo", "WechatClient"))); tasklist.Add(factory.StartNew(() => this.coding("ToTo", "EAServer"))); //ContinueWhenAny会开一个新的子线程 //ContinueWhenAll会开一个新的子线程 tasklist.Add(factory.ContinueWhenAny(tasklist.ToArray(), t => Console.WriteLine("获得大红包 id={0}", Thread.CurrentThread.ManagedThreadId))); tasklist.Add(factory.ContinueWhenAll(tasklist.ToArray(), tlist => Console.WriteLine("开始联调、部署、测试、验收 {0}", Thread.CurrentThread.ManagedThreadId))); //某个模块完成后收取20% Task.WaitAny(tasklist.ToArray()); //任一子线程结束;卡住当前线程,让程序完成等待 Console.WriteLine("某个模块完成后, 收取剩下的20%"); //开发完成后收钱 Task.WaitAll(tasklist.ToArray()); //等待所有子线程结束;卡住当前线程,让程序完成等待 Console.WriteLine("收取剩下的30%"); Console.WriteLine("************************btnTask_Click end*************************"); } private void coding(string username,string projectname) { Console.WriteLine("{0} {1} start coding {2},线程id={3}", DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss.fff"), username, projectname,Thread.CurrentThread.ManagedThreadId); int icount = 0; for (int i = 0; i < 1000000000; i++) { icount = i; } Console.WriteLine("{0} {1} end coding {2},线程id={3}", DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss.fff"), username, projectname, Thread.CurrentThread.ManagedThreadId); }
运行结果