Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách hủy luồng (destroy threads) trong C#?

Phương thức Abort() được dùng để hủy luồng.

Runtime hủy luồng bằng cách ném ThreadAbortException. Ngoại lệ này không thể bị bắt, điều khiển được gửi đến khối finally, nếu có.

Dưới đây là ví dụ cho thấy cách hủy luồng:

Ví dụ

using System; 
using System.Threading; 
namespace MultithreadingApplication { 
    class ThreadCreationProgram { 
        public static void CallToChildThread() { 
            try { 
                Console.WriteLine("Child thread starts"); 
                // làm việc gì đó, như đếm đến 10 
                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"); 
            } finally { 
                Console.WriteLine("Couldn't catch the Thread Exception"); 
            } 
        } 
        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(); 
            // dừng luồng chính một chút 
            Thread.Sleep(2000); 
            // bây giờ hủy luồng con 
            Console.WriteLine("In Main: Aborting the Child thread"); 
            childThread.Abort(); 
            Console.ReadKey(); 
        } 
    } 
}

Kết quả

In Main: Creating the Child thread Child thread starts 0 1 2 In Main: Aborting the Child thread Thread Abort Exception Couldn't catch the Thread Exception