1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Diagnostics; 6 using System.Drawing; 7 using System.Linq; 8 using System.Text; 9 using System.Threading; 10 using System.Threading.Tasks; 11 using System.Windows.Forms; 12 13 namespace 多线程 14 { 15 public partial class Form1 : Form 16 { 17 public Form1() 18 { 19 InitializeComponent(); 20 } 21 22 /// <summary> 23 /// 启用Task多线程 24 /// </summary> 25 /// <param name="sender"></param> 26 /// <param name="e"></param> 27 private void task_Click(object sender, EventArgs e) 28 { 29 List<Task> taskList = new List<Task>(); 30 TaskFactory taskFactory = new TaskFactory(); 31 32 Console.WriteLine("=======>>>>开始"); 33 Action act1 = new Action(() => GetSum("张三")); 34 Action act2 = new Action(()=>GetSum("李四")); 35 Action act3 = new Action(()=>GetSum("王五")); 36 taskList.Add(taskFactory.StartNew(act1)); 37 taskList.Add(taskFactory.StartNew(act2)); 38 taskList.Add(taskFactory.StartNew(act3)); 39 40 Action<Task[]> actAll = new Action<Task[]>(t => 41 { 42 Console.WriteLine("任务结束,开始执行联调。当前线程ID是{0}", Thread.CurrentThread.ManagedThreadId); 43 Console.WriteLine("======>>>>>>完成"); 44 }); 45 46 47 //只是等待某一个任务完成就可以结束或者继续再等待剩余的任务完成 48 Task.WaitAny(taskList.ToArray()); 49 Console.WriteLine("一个任务已经完成了!!!!!!"); 50 51 taskFactory.ContinueWhenAll(taskList.ToArray(), actAll); 52 53 54 //等待所有子线程任务完成,这种方法会卡住主线程 55 //Task.WaitAll(new Task[] {taskAll}); 56 57 } 58 59 private void GetSum(string name) 60 { 61 long sum = 0; 62 Stopwatch watch = new Stopwatch(); 63 watch.Start(); 64 for (int i = 0; i < 1000000000; i++) 65 { 66 sum += i; 67 } 68 watch.Stop(); 69 Console.WriteLine("当前是:{0}在执行任务,sum结果是:{1},当前线程ID是{2},执行时间是{3}",name,sum,Thread.CurrentThread.ManagedThreadId,watch.ElapsedMilliseconds); 70 } 71 } 72 }