示例代码:
1 static void Main(string[] args) 2 { 3 ThreadPool.SetMaxThreads(4, 1000); 4 object locker = new object(); 5 const int TaskCount = 10; 6 7 Task main = Task.Run(() => 8 { 9 var mainTid = Thread.CurrentThread.ManagedThreadId; 10 Console.WriteLine("Main TID:{0}", mainTid); 11 Thread.Sleep(1000); 12 13 Task[] tasks = new Task[TaskCount]; 14 for (int i = 0; i < TaskCount; i++) 15 { 16 tasks[i] = Task.Run(() => 17 { 18 var tid = Thread.CurrentThread.ManagedThreadId; 19 lock (locker) 20 { 21 if (mainTid == tid) 22 Console.ForegroundColor = ConsoleColor.Red; 23 Console.WriteLine(tid); 24 if (mainTid == tid) 25 Console.ForegroundColor = ConsoleColor.Gray; 26 } 27 Thread.Sleep(1000); 28 }); 29 } 30 Task.WaitAll(tasks); 31 }); 32 main.Wait(); 33 }