using System;
using System.Threading;
namespace ThreadPoolExample
{
class Program
{
static void Main(string[] args)
{
int maxWorkerThreads, maxCompletionPortThreads;
ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxCompletionPortThreads);
ThreadPool.SetMaxThreads(5, maxCompletionPortThreads);
for (int i = 0; i < 20; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(Task), i);
}
Console.ReadLine();
}
static void Task(object state)
{
Console.WriteLine("Task {0} is running on a thread from the thread pool.", state);
Thread.Sleep(1000); Console.WriteLine("Task {0} exited.", state);
}
}
}
会输出: Task 18 is running on a thread from the thread pool. Task 4 is running on a thread from the thread pool. Task 13 is running on a thread from the thread pool. Task 19 is running on a thread from the thread pool. Task 16 is running on a thread from the thread pool. Task 8 is running on a thread from the thread pool. Task 1 is running on a thread from the thread pool. Task 3 is running on a thread from the thread pool. Task 2 is running on a thread from the thread pool. Task 9 is running on a thread from the thread pool. Task 14 is running on a thread from the thread pool. Task 17 is running on a thread from the thread pool. Task 0 is running on a thread from the thread pool. Task 5 is running on a thread from the thread pool. Task 10 is running on a thread from the thread pool. Task 11 is running on a thread from the thread pool. Task 12 is running on a thread from the thread pool. Task 7 is running on a thread from the thread pool. Task 6 is running on a thread from the thread pool. Task 15 is running on a thread from the thread pool. Task 8 exited. Task 3 exited. Task 2 exited. Task 4 exited. Task 18 exited. Task 0 exited. Task 1 exited. Task 5 exited. Task 13 exited. Task 19 exited. Task 16 exited. Task 9 exited. Task 14 exited. Task 10 exited. Task 11 exited. Task 12 exited. Task 7 exited. Task 6 exited. Task 15 exited. Task 17 exited.