EN
C#/.NET - thread pool
13 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.
Quick solution:
xxxxxxxxxx
1
// using System;
2
// using System.Threading;
3
4
WaitCallback callback = (object arg) =>
5
{
6
string cast = arg as string;
7
8
// ...
9
};
10
11
ThreadPool.QueueUserWorkItem(callback, "arg 1");
12
ThreadPool.QueueUserWorkItem(callback, "arg 2");
13
ThreadPool.QueueUserWorkItem(callback, "arg 3");
14
// ...
15
ThreadPool.QueueUserWorkItem(callback, "arg N");
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
for (int i = 0; i < tasksCount; ++i)
27
{
28
int taskId = i + 1;
29
30
ThreadPool.QueueUserWorkItem(callback, taskId);
31
//ThreadPool.QueueUserWorkItem(myTask.Execute, taskId);
32
//ThreadPool.QueueUserWorkItem(new WaitCallback(myTask.Execute), taskId);
33
}
34
35
Thread.Sleep(1000);
36
}
37
}
38
}
Output:
xxxxxxxxxx
1
Task 3/5: Iteration 1/5
2
Task 1/5: Iteration 1/5
3
Task 1/5: Iteration 2/5
4
Task 1/5: Iteration 3/5
5
Task 1/5: Iteration 4/5
6
Task 1/5: Iteration 5/5
7
Task 4/5: Iteration 1/5
8
Task 4/5: Iteration 2/5
9
Task 4/5: Iteration 3/5
10
Task 4/5: Iteration 4/5
11
Task 4/5: Iteration 5/5
12
Task 2/5: Iteration 1/5
13
Task 2/5: Iteration 2/5
14
Task 2/5: Iteration 3/5
15
Task 2/5: Iteration 4/5
16
Task 3/5: Iteration 2/5
17
Task 5/5: Iteration 1/5
18
Task 5/5: Iteration 2/5
19
Task 5/5: Iteration 3/5
20
Task 5/5: Iteration 4/5
21
Task 5/5: Iteration 5/5
22
Task 2/5: Iteration 5/5
23
Task 3/5: Iteration 3/5
24
Task 3/5: Iteration 4/5
25
Task 3/5: Iteration 5/5
Note: Code has been run with 4 cores CPU.