Thread Class ใน C#: Properties และ Methods
System.Threading.Thread คลาสหลักสำหรับจัดการ Thread แบบ Manual (Low-level) ปัจจุบันแนะนำให้ใช้ Task/ThreadPool แทน
Properties สำคัญ
| Property | คำอธิบาย |
CurrentThread | Static: ได้ Thread ปัจจุบัน |
CurrentContext | Context ที่ Thread กำลัง Execute |
CurrentCulture | CultureInfo สำหรับ Thread นี้ (Formatting) |
CurrentUICulture | Culture สำหรับ Resource Manager |
IsAlive | Thread ทำงานอยู่หรือไม่ |
IsBackground | Background Thread (ไม่กัน Process Exit) |
IsThreadPoolThread | เป็น Thread Pool Thread หรือไม่ |
ManagedThreadId | Unique ID ของ Managed Thread |
Name | ชื่อ Thread (สำหรับ Debug) |
Priority | Priority Level (Lowest..Highest) |
ThreadState | State ปัจจุบัน (Running, WaitSleepJoin, Stopped, etc.) |
Methods สำคัญ
| Method | คำอธิบาย |
Start() | เริ่ม Thread |
Sleep(ms) | Static: หยุด Thread ปัจจุบัน |
Join() | รอ Thread จบการทำงาน |
Abort() | Deprecated ยกเลิก Thread (Dangerous) |
Interrupt() | Interrupt Thread ที่ Wait/Sleep/Join |
Yield() | Static: ให้ CPU ให้ Thread อื่น |
GetData/SetData | Thread Local Storage (LocalDataStoreSlot) |
BeginCriticalRegion/EndCriticalRegion | แจ้ง Host เกี่ยวกับ Critical Code Region |
BeginThreadAffinity/EndThreadAffinity | แจ้ง Host เกี่ยวกับ Thread Affinity |
ตัวอย่าง: ใช้ Properties และ Methods พื้นฐาน
using System;
using System.Threading;
class Program
{
static void Main()
{
Thread t = Thread.CurrentThread;
t.Name = "MainThread";
Console.WriteLine($"Thread ID: {t.ManagedThreadId}");
Console.WriteLine($"Name: {t.Name}");
Console.WriteLine($"IsAlive: {t.IsAlive}");
Console.WriteLine($"IsBackground: {t.IsBackground}");
Console.WriteLine($"Priority: {t.Priority}");
Console.WriteLine($"Culture: {t.CurrentCulture.Name}");
// สร้าง Child Thread
Thread child = new Thread(() =>
{
Thread.CurrentThread.Name = "Worker";
Console.WriteLine($"Child: {Thread.CurrentThread.Name} started");
Thread.Sleep(1000);
Console.WriteLine($"Child: {Thread.CurrentThread.Name} finished");
});
child.IsBackground = true; // ไม่กัน App Exit
child.Start();
child.Join(); // รอ Child จบ
Console.WriteLine("Main finished");
}
}
⚠️ Deprecated / Dangerous Methods
Abort() - อาจทิ้ง Lock, Corrupt State, ไม่สามารถ Catch ได้สมบูรณ์
Suspend()/Resume() - Deadlock Risk
- ใช้
CancellationToken และ Task แทน