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

Abort (Hủy) Thread trong C#

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

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

Dùng Abort() trên thread:

childThread.Abort();

Ví dụ

using System;
using System.Threading;

namespace MultithreadingApplication {
    class ThreadCreationProgram {
        public static void CallToChildThread() {
            try {
                Console.WriteLine("Child thread bắt đầu");
                for (int counter = 0; counter <= 10; counter++) {
                    Thread.Sleep(500);
                    Console.WriteLine(counter);
                }
                Console.WriteLine("Child Thread Hoàn thành");
            } catch (ThreadAbortException e) {
                Console.WriteLine("Thread Abort Exception");
            } finally {
                Console.WriteLine("Không thể bắt Thread Exception");
            }
        }
        static void Main(string[] args) {
            ThreadStart childref = new ThreadStart(CallToChildThread);
            Console.WriteLine("Trong Main: Tạo Child thread");
            Thread childThread = new Thread(childref);
            childThread.Start();
            // dừng main thread một lúc
            Thread.Sleep(5000);
            // hủy child thread
            Console.WriteLine("Trong Main: Hủy Child thread");
            childThread.Abort();
            Console.ReadKey();
        }
    }
}

Kết quả

Trong Main: Tạo Child thread
Child thread bắt đầu
0
1
2
3
4
5
6
7
8
Trong Main: Hủy Child thread
Thread Abort Exception
Không thể bắt Thread Exception