示例代码:
static void Main(string[] args)
{
ThreadPool.SetMaxThreads(, );
object locker = new object();
const int TaskCount = ; Task main = Task.Run(() =>
{
var mainTid = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("Main TID:{0}", mainTid);
Thread.Sleep(); Task[] tasks = new Task[TaskCount];
for (int i = ; i < TaskCount; i++)
{
tasks[i] = Task.Run(() =>
{
var tid = Thread.CurrentThread.ManagedThreadId;
lock (locker)
{
if (mainTid == tid)
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(tid);
if (mainTid == tid)
Console.ForegroundColor = ConsoleColor.Gray;
}
Thread.Sleep();
});
}
Task.WaitAll(tasks);
});
main.Wait();
}