ใน C# property ManagedThreadId ของคลาส Thread คืนค่ารหัสตัวเลขเฉพาะ (unique identifier) ของ managed thread ปัจจุบัน ใช้สำหรับการ debug, logging, หรือติดตามเธรดในระบบ multi-threaded
ตัวอย่างโค้ดที่ 1: Thread ธรรมดา และ Thread Pool
using System;
using System.Threading;
public class Demo
{
public static void Main()
{
Thread thread = new Thread(new ThreadStart(Demo1));
ThreadPool.QueueUserWorkItem(new WaitCallback(Demo2));
Console.WriteLine("ManagedThreadId = " + thread.ManagedThreadId);
}
public static void Demo1()
{
Thread.Sleep(2000);
}
public static void Demo2(object stateInfo)
{
Console.WriteLine("Thread belongs to managed thread pool? = " + Thread.CurrentThread.IsThreadPoolThread);
}
}
ผลลัพธ์
ManagedThreadId = 3
Thread belongs to managed thread pool? = True
ตัวอย่างโค้ดที่ 2: เริ่ม Thread และดู ManagedThreadId
using System;
using System.Threading;
public class Demo
{
public static void Main()
{
Thread thread = new Thread(new ThreadStart(Demo));
Console.WriteLine("ManagedThreadId = " + thread.ManagedThreadId);
thread.Start();
}
public static void Demo()
{
Console.WriteLine("Thread belongs to managed thread pool? = " + Thread.CurrentThread.IsThreadPoolThread);
}
}
ผลลัพธ์
ManagedThreadId = 3
Thread belongs to managed thread pool? = False
ข้อสังเกตสำคัญ
ManagedThreadIdเป็น int ที่ unique ภายใน process- ค่าไม่เปลี่ยนแปลงตลอดอายุของเธรด
- Thread pool threads ก็มี ManagedThreadId ของตัวเอง
Thread.CurrentThread.ManagedThreadIdให้ ID ของเธรดที่กำลังรันโค้ดอยู่- ใช้สำหรับ logging, debugging, profiling
Thread vs ThreadPool vs Task
| คุณสมบัติ | Thread | ThreadPool | Task / Task<T> |
|---|---|---|---|
| ManagedThreadId | มี (คงที่) | มี (คงที่) | มี (อาจเปลี่ยนระหว่าง await) |
| IsThreadPoolThread | false | true | มักเป็น true |
| Overhead | สูง (1MB stack) | ต่ำ (reuse threads) | ต่ำมาก |
| แนะนำสำหรับ | Long-running, dedicated | Short work items | ทุกอย่างสมัยใหม่ |
แนวทางปฏิบัติที่ดี
- ใช้
Task.Run()หรือasync/awaitแทนการสร้าง Thread โดยตรง - ใช้
Thread.CurrentThread.ManagedThreadIdใน log เพื่อ trace execution flow - หลีกเลี่ยงการเก็บ ManagedThreadId ไว้ใช้ตัดสินใจ logic (thread อาจถูก reuse)