1 class Program 2 { 3 static List<Task> tkList = new List<Task>(); 4 static int taskCount = 5; 5 static object obj = new object(); 6 7 static void Main(string[] args) 8 { 9 Console.WriteLine("开始任务"); 10 for (int i = 0; i < 100; i++) 11 { 12 while(!isGo()) 13 { 14 Thread.Sleep(100); 15 } 16 Action<object> action = action = new Action<object>(Print); 17 CreatTask(action, i); 18 } 19 Console.WriteLine("任务完成!"); 20 Console.Read(); 21 } 22 23 24 public static bool isGo() 25 { 26 bool flag =false; 27 28 if (tkList.Count == 0||tkList.Count < taskCount) 29 { 30 flag = true; 31 } 32 else 33 { 34 foreach (Task item in tkList) 35 { 36 if (item.IsCompleted) 37 { 38 Console.WriteLine(item.AsyncState.ToString()); 39 tkList.Remove(item); 40 item.Dispose(); 41 flag = true; 42 break; 43 } 44 } 45 } 46 return flag; 47 } 48 49 public static void CreatTask(Action<object> action,object obj) 50 { 51 Task t = Task.Factory.StartNew(action, obj); 52 tkList.Add(t); 53 } 54 55 public static void Print(object msg) 56 { 57 Console.WriteLine(msg); 58 } 59 }