ภาพรวม
คุณสมบัติ Thread.CurrentThread.IsThreadPoolThread บอกว่าเธรดที่กำลังทำงานอยู่เป็นเธรดจาก managed thread pool (.NET ThreadPool) หรือเป็นเธรดที่สร้างเอง (manual thread)
ตัวอย่างที่ 1: เธรดที่สร้างด้วย Thread ใหม่ (ไม่ใช่ Thread Pool)
using System;
using System.Threading;
public class Demo
{
public static void Main()
{
Thread thread = new Thread(new ThreadStart(demo));
thread.Start();
}
public static void demo()
{
Console.WriteLine("Thread belongs to managed thread pool? = " + Thread.CurrentThread.IsThreadPoolThread);
}
}
ผลลัพธ์
Thread belongs to managed thread pool? = False
ตัวอย่างที่ 2: เธรดจาก ThreadPool.QueueUserWorkItem (เป็น Thread Pool)
using System;
using System.Threading;
public class Demo
{
public static void Main()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(demo));
Console.ReadLine(); // รอให้เธรด pool ทำงานเสร็จ
}
public static void demo(object stateInfo)
{
Console.WriteLine("Thread belongs to managed thread pool? = " + Thread.CurrentThread.IsThreadPoolThread);
}
}
ผลลัพธ์
Thread belongs to managed thread pool? = True
คำอธิบายเพิ่มเติม
- Thread Pool จัดการเธรดให้อัตโนมัติ ลดค่าใช้จ่ายในการสร้าง/ทำลายเธรด เหมาะสำหรับงานสั้นๆ (short-lived tasks)
ThreadPool.QueueUserWorkItemคิวงานให้เธรด pool ประมวลผล- เธรดจาก Thread Pool เป็น background threads (IsBackground = true) โปรแกรมจะจบได้แม้เธรดยังทำงานอยู่
- สำหรับงานยาวหรือต้องการควบคุมเธรดโดยตรง ใช้
Task(TPL) หรือThreadโดยตรง Task.Run()ใช้ Thread Pool ด้วย (IsThreadPoolThread = true)