C# 中的 Abort
csharpprogrammingserver side programming更新于 2025/9/19 7:35:00
Abort() 方法用于销毁线程。
运行时通过抛出 ThreadAbortException 来中止线程。此异常无法捕获,如果有,则将控制权发送给 finally 块。
在线程上使用 Abort() 方法 −
childThread.Abort();
示例
using System;
using System.Threading;
namespace MultithreadingApplication {
class ThreadCreationProgram {
public static void CallToChildThread() {
try {
Console.WriteLine("子线程启动");
// 做一些工作,比如数到 10
for (int counter = 0; counter <= 10; counter++) {
Thread.Sleep(500);
Console.WriteLine(counter);
}
Console.WriteLine("子线程已完成");
} catch (ThreadAbortException e) {
Console.WriteLine("线程中止异常");
} finally {
Console.WriteLine("无法捕获线程异常");
}
}
static void Main(string[] args) {
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("在 Main 中:创建子线程");
Thread childThread = new Thread(childref);
childThread.Start();
//暂停主线程一段时间
Thread.Sleep(5000);
//现在中止子线程
Console.WriteLine("在 Main 中:中止子线程");
childThread.Abort();
Console.ReadKey();
}
}
}
输出
在 Main 中:创建子线程 子线程启动 0 1 2 3 4 5 6 7 8 在 Main 中:中止子线程 线程中止异常 无法捕获线程异常

