Thuộc tính Thread.CurrentThread.IsThreadPoolThread cho biết luồng hiện tại có phải là luồng từ managed thread pool hay không. Luồng tạo thủ công bằng new Thread trả về false, trong khi luồng từ ThreadPool.QueueUserWorkItem trả về true.
Ví dụ 1: Luồng tạo thủ công
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("Luồng thuộc managed thread pool? = " + Thread.CurrentThread.IsThreadPoolThread);
}
}
Kết quả
Luồng thuộc managed thread pool? = False
Ví dụ 2: Luồng từ ThreadPool
using System;
using System.Threading;
public class Demo
{
public static void Main()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(demo));
}
public static void demo(object stateInfo)
{
Console.WriteLine("Luồng thuộc managed thread pool? = " + Thread.CurrentThread.IsThreadPoolThread);
}
}
Kết quả
Luồng thuộc managed thread pool? = True
Ứng dụng: Kiểm tra này hữu ích khi bạn cần điều chỉnh hành vi (ví dụ: logging, synchronization) tùy thuộc vào nguồn gốc luồng.