EN
C#/.NET - max and min number of threads in thread pool
5 points
To set up max and min number of threads in ThreadPool
class, ThreadPool.SetMinThreads
and ThreadPool.SetMaxThreads
methods could be useful.
xxxxxxxxxx
1
using System;
2
using System.Threading;
3
4
namespace Test
5
{
6
public class Program
7
{
8
static void Main(string[] args)
9
{
10
int tasksCount = 5;
11
int iterationsCount = 5;
12
13
WaitCallback callback = (object state) =>
14
{
15
int taskId = (int)state;
16
17
for (int i = 0; i < iterationsCount; ++i)
18
{
19
int iterationId = i + 1;
20
21
Console.WriteLine("Task " + taskId + "/" + tasksCount
22
+ ": Iteration " + iterationId + "/" + iterationsCount);
23
}
24
};
25
26
ThreadPool.SetMinThreads(1, 1);
27
ThreadPool.SetMaxThreads(2, 2);
28
29
for (int i = 0; i < tasksCount; ++i)
30
{
31
int taskId = i + 1;
32
33
ThreadPool.QueueUserWorkItem(callback, taskId);
34
}
35
36
Thread.Sleep(1000);
37
}
38
}
39
}
Output:
xxxxxxxxxx
1
Task 1/5: Iteration 1/5
2
Task 2/5: Iteration 1/5
3
Task 2/5: Iteration 2/5
4
Task 2/5: Iteration 3/5
5
Task 1/5: Iteration 2/5
6
Task 1/5: Iteration 3/5
7
Task 1/5: Iteration 4/5
8
Task 1/5: Iteration 5/5
9
Task 2/5: Iteration 4/5
10
Task 2/5: Iteration 5/5
11
Task 3/5: Iteration 1/5
12
Task 3/5: Iteration 2/5
13
Task 3/5: Iteration 3/5
14
Task 3/5: Iteration 4/5
15
Task 3/5: Iteration 5/5
16
Task 4/5: Iteration 1/5
17
Task 4/5: Iteration 2/5
18
Task 4/5: Iteration 3/5
19
Task 4/5: Iteration 4/5
20
Task 4/5: Iteration 5/5
21
Task 5/5: Iteration 1/5
22
Task 5/5: Iteration 2/5
23
Task 5/5: Iteration 3/5
24
Task 5/5: Iteration 4/5
25
Task 5/5: Iteration 5/5
Note: Notice that, only 2 tasks are executed in the same time.