Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

C#/.NET - thread pool

0 contributions
10 points

Sometimes it is necessary to create a lot of threads in short time. When task is small, the time of thread creating and destroying could take more time than task execution. To solve this problem ThreadPool class is useful. It manages of thread pool and brings threads ready to execute tasks. After task executed puts thread back to pool for next tasks to save resources speeding up all.

1. ThreadPool.QueueUserWorkItem method example

using System;
using System.Threading;

namespace Test
{
	public class Program
	{
		static void Main(string[] args)
		{
			int tasksCount = 5;
			int iterationsCount = 5;

			WaitCallback callback = (object state) =>
			{
				int taskId = (int)state;

				for (int i = 0; i < iterationsCount; ++i)
				{
					int iterationId = i + 1;

					Console.WriteLine("Task " + taskId + "/" + tasksCount 
						+ ": Iteration " + iterationId + "/" + iterationsCount);
				}
			};

			for (int i = 0; i < tasksCount; ++i)
			{
				int taskId = i + 1;

				ThreadPool.QueueUserWorkItem(callback, taskId);
				//ThreadPool.QueueUserWorkItem(myTask.Execute, taskId);
				//ThreadPool.QueueUserWorkItem(new WaitCallback(myTask.Execute), taskId);
			}

			Thread.Sleep(1000);
		}
	}
}

Output:

Task 3/5: Iteration 1/5
Task 1/5: Iteration 1/5
Task 1/5: Iteration 2/5
Task 1/5: Iteration 3/5
Task 1/5: Iteration 4/5
Task 1/5: Iteration 5/5
Task 4/5: Iteration 1/5
Task 4/5: Iteration 2/5
Task 4/5: Iteration 3/5
Task 4/5: Iteration 4/5
Task 4/5: Iteration 5/5
Task 2/5: Iteration 1/5
Task 2/5: Iteration 2/5
Task 2/5: Iteration 3/5
Task 2/5: Iteration 4/5
Task 3/5: Iteration 2/5
Task 5/5: Iteration 1/5
Task 5/5: Iteration 2/5
Task 5/5: Iteration 3/5
Task 5/5: Iteration 4/5
Task 5/5: Iteration 5/5
Task 2/5: Iteration 5/5
Task 3/5: Iteration 3/5
Task 3/5: Iteration 4/5
Task 3/5: Iteration 5/5
Note: Code has been run with 4 cores CPU.

2. See also

  1. C#/.NET - max and min number of threads in thread pool

3. Resources

  1. ThreadPool Class - Microsoft Docs
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more