线程已被中止- “Thread was being aborted”
遇到过这个exception么? 这个exception是为什么而产生的呢?
下面的代码段来自MSDN, 很有说明性.
简单来说, 就是当进程还想继续执行的时候, 发现自己已经被调用过Abort方法了. 既然自己作为线程已经被中止, 就无法执行罗, 于是exception丢了出来.
下面的代码来自MSDN, 说明问题:
The following example demonstrates aborting a thread. The thread that receives the ThreadAbortException uses the ResetAbort method to cancel the abort request and continue executing.
1: using System;
2: using System.Threading;
3: using System.Security.Permissions;
4:
5: public class ThreadWork {
6: public static void DoWork() {
7: try {
8: for(int i=0; i<100; i++) {
9: Console.WriteLine("Thread - working.");
10: Thread.Sleep(100);
11: }
12: }
13: catch(ThreadAbortException e) {
14: Console.WriteLine("Thread - caught ThreadAbortException - resetting.");
15: Console.WriteLine("Exception message: {0}", e.Message);
16: Thread.ResetAbort();
17: }
18: Console.WriteLine("Thread - still alive and working.");
19: Thread.Sleep(1000);
20: Console.WriteLine("Thread - finished working.");
21: }
22: }
23:
24: class ThreadAbortTest {
25: public static void Main() {
26: ThreadStart myThreadDelegate = new ThreadStart(ThreadWork.DoWork);
27: Thread myThread = new Thread(myThreadDelegate);
28: myThread.Start();
29: Thread.Sleep(100);
30: Console.WriteLine("Main - aborting my thread.");
31: myThread.Abort();
32: myThread.Join();
33: Console.WriteLine("Main ending.");
34: }
35: }
下面是输出结果:
Thread - working.
Main - aborting my thread.
Thread - caught ThreadAbortException - resetting.
Exception message: Thread was being aborted.
Thread - still alive and working.
Thread - finished working.
Main ending.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律