Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีทำลาย Thread ใน C# (Thread.Abort)

Thread.Abort() ใช้ทำลาย Thread โดยโยน ThreadAbortException ไม่สามารถ Catch ได้ (จะ Re-throw อัตโนมัติหลัง finally)

ตัวอย่าง

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();
            
            // หยุด Main thread 2 วินาที
            Thread.Sleep(2000);
            
            // Abort Child Thread
            Console.WriteLine("In Main: Aborting the Child thread");
            childThread.Abort();
            
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

In Main: Creating the Child thread
Child thread starts
0
1
2
In Main: Aborting the Child thread
Thread Abort Exception caught
Finally block executed - cleanup here

⚠️ ข้อควรระวัง (สำคัญมาก)

  • Thread.Abort() ถูก Deprecated แล้ว (.NET Core / .NET 5+ ไม่รองรับ)
  • อาจทำให้เกิด Deadlock, Corrupted State, Resource Leaks
  • ไม่ควรใช้ใน Production Code

ทางเลือกที่ดีกว่า: CancellationToken

using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        var cts = new CancellationTokenSource();
        var token = cts.Token;
        
        Task.Run(() => 
        {
            for (int i = 0; i < 10; i++)
            {
                token.ThrowIfCancellationRequested(); // Check cancellation
                Thread.Sleep(500);
                Console.WriteLine(i);
            }
            Console.WriteLine("Completed");
        }, token);
        
        Thread.Sleep(2000);
        Console.WriteLine("Requesting cancellation...");
        cts.Cancel(); // ส่งสัญญาณยกเลิก
        
        Console.ReadKey();
    }
}