Thread Pool là tập hợp các luồng worker được quản lý tự động bởi CLR, dùng để thực thi các tác vụ nền (background tasks) hiệu quả thay vì tạo/hủy luồng thủ công liên tục.
Cách sử dụng ThreadPool.QueueUserWorkItem
Đưa phương thức (delegate) vào hàng đợi để thread pool thực thi khi có luồng rảnh.
Mã nguồn
using System;
using System.Threading;
class Demo {
public void one(object o) {
for (int i = 0; i <= 3; i++) {
Console.WriteLine("One executed");
}
}
public void two(object o) {
for (int i = 0; i <= 3; i++) {
Console.WriteLine("Two executed");
}
}
public void three(object o) {
for (int i = 0; i <= 3; i++) {
Console.WriteLine("Three executed");
}
}
static void Main() {
Demo d = new Demo();
for (int i = 0; i < 3; i++) {
ThreadPool.QueueUserWorkItem(new WaitCallback(d.one));
ThreadPool.QueueUserWorkItem(new WaitCallback(d.two));
ThreadPool.QueueUserWorkItem(new WaitCallback(d.three));
}
Console.Read();
}
}
Kết quả (mẫu - thứ tự có thể khác mỗi lần chạy)
Two executed
Two executed
Two executed
Two executed
One executed
One executed
One executed
One executed
Three executed
Three executed
...
Giải thích
ThreadPool.QueueUserWorkItem: Đăng ký tác vụ (callback) vào thread pool.WaitCallback: Delegate nhận tham sốobject.- Các tác vụ chạy song song (parallel) và không theo thứ tự xác định.
- Thread pool tự quản lý số lượng luồng tối ưu cho CPU.
Khi nào dùng Thread Pool?
- Tác vụ ngắn, I/O-bound (đọc file, request web, query DB...)
- Không cần kiểm soát chi tiết vòng đời luồng.
- Tránh overhead tạo/hủy luồng liên tục.
Lưu ý
Không dùng Thread Pool cho tác vụ dài (long-running), chặn UI, hoặc cần ưu tiên/đồng bộ phức tạp — hãy dùng Task (TPL) hoặc Thread chuyên biệt.