When I am learning Thread Pool in C# yesterday, I tried to create an example that will create a Thread Pool that enables two thread to enter the Thread Pool(MaxThreads
) while give it 4 assignment in total. Here is my code:
static void Main(string[] args)
{
ThreadPoolExample_0();
while (true)
{
Thread.Sleep(2000);
}
}
public static void ThreadPoolExample_0()
{
ThreadPool.SetMaxThreads(2,2);
for (int i = 0; i < 4; 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);
}
However, it will output this dialog, which means that thread will enter the Thread Pool even it is full. Here is the dialog:
Task 3 is running on a thread from the thread pool.
Task 0 is running on a thread from the thread pool.
Task 1 is running on a thread from the thread pool.
Task 2 is running on a thread from the thread pool.
Task 0 exited.
Task 3 exited.
Task 1 exited.
Task 2 exited.
I wonder what's wrong with my code, or if my understanding of the C# thread pool is incorrect.