เมธอด Thread.Abort() ใน C#
Thread.Abort() ใช้ยกเลิกเธรดโดยบังคับ โดยการโยน ThreadAbortException ในเธรดเป้าหมาย แต่เป็น Legacy API ที่ Deprecated แล้วใน .NET Core/.NET 5+
ตัวอย่างการใช้งาน (Legacy)
using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
try
{
Console.WriteLine("Child thread starts");
for (int counter = 0; counter <= 10; counter++)
{
Thread.Sleep(500);
Console.WriteLine(counter);
}
Console.WriteLine("Child Thread Completed");
}
catch (ThreadAbortException e)
{
Console.WriteLine("Thread Abort Exception caught");
}
finally
{
Console.WriteLine("Finally block executed - cleanup here");
}
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
// หน่วงเวลา 5 วินาที
Thread.Sleep(5000);
// Abort เธรดลูก
Console.WriteLine("In Main: Aborting the Child thread");
childThread.Abort();
Console.ReadKey();
}
}
}
ผลลัพธ์ตัวอย่าง
In Main: Creating the Child thread
Child thread starts
0
1
2
3
4
5
6
7
8
In Main: Aborting the Child thread
Thread Abort Exception caught
Finally block executed - cleanup here
ทำไม Abort() ถูก Deprecated?
| ปัญหา | คำอธิบาย |
|---|---|
| Unpredictable state | เธรดถูกหยุดกลางคัน อาจทิ้ง lock, resource, หรือข้อมูลในสภาพเสียหาย |
| Cannot be reliably caught | ThreadAbortException จะ re-throw อัตโนมัติหลัง catch block (เว้นแต่ ResetAbort()) |
| Corrupted locks | หาก abort ขณะ hold lock → deadlock หรือ data corruption |
| No .NET Core support | PlatformNotSupportedException ใน .NET Core/.NET 5+ |
แนวทางทดแทนที่แนะนำ (Modern Approach)
1. CancellationToken (Cooperative Cancellation)
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var cts = new CancellationTokenSource();
Task worker = Task.Run(() => DoWork(cts.Token), cts.Token);
await Task.Delay(2000);
Console.WriteLine("Requesting cancellation...");
cts.Cancel(); // ส่งสัญญาณยกเลิก
try
{
await worker; // รอจบ (อาจโยน OperationCanceledException)
}
catch (OperationCanceledException)
{
Console.WriteLine("Worker cancelled gracefully");
}
}
static void DoWork(CancellationToken token)
{
for (int i = 0; i < 10; i++)
{
token.ThrowIfCancellationRequested(); // ตรวจสอบและโยนถ้าถูก cancel
Console.WriteLine($"Working... {i}");
Thread.Sleep(500);
}
}
}
2. Boolean Flag (Simple)
volatile bool _shouldStop = false;
void Worker()
{
while (!_shouldStop)
{
// Do work
}
}
void Stop() => _shouldStop = true;
3. Task.Run with Cancellation
var cts = new CancellationTokenSource();
var task = Task.Run(() => LongRunningOperation(cts.Token), cts.Token);
// Later...
cts.CancelAfter(TimeSpan.FromSeconds(5)); // Auto-cancel after 5s
สรุป
- อย่าใช้ Thread.Abort() ในโค้ดใหม่
- ใช้ CancellationToken สำหรับ Cooperative Cancellation
- ออกแบบโค้ดให้ตรวจสอบ Token/Flag เป็นระยะ
- ทำความสะอาดทรัพยากรใน
finallyหรือusing