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 think you have some skills to help others

help someone and become a part of our community - List Q & A

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

0 contributions
5 points

To set up max and min number of threads in ThreadPool class, ThreadPool.SetMinThreads and ThreadPool.SetMaxThreads methods could be useful.

1. Max and min number of threads 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);
				}
			};

			ThreadPool.SetMinThreads(1, 1);
			ThreadPool.SetMaxThreads(2, 2);

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

				ThreadPool.QueueUserWorkItem(callback, taskId);
			}

			Thread.Sleep(1000);
		}
	}
}

Output:

Task 1/5: Iteration 1/5
Task 2/5: Iteration 1/5
Task 2/5: Iteration 2/5
Task 2/5: Iteration 3/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 2/5: Iteration 4/5
Task 2/5: Iteration 5/5
Task 3/5: Iteration 1/5
Task 3/5: Iteration 2/5
Task 3/5: Iteration 3/5
Task 3/5: Iteration 4/5
Task 3/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 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
 Note: Notice that, only 2 tasks are executed in the same time.

2. Resources

  1. ThreadPool Class - Microsoft Docs
  2. ThreadPool.SetMinThreads - Microsoft Docs
  3. ThreadPool.SetMaxThreads - Micosoft 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