线程已被中止- “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.

posted on   中道学友  阅读(13248)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律

导航

< 2010年1月 >
27 28 29 30 31 1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31 1 2 3 4 5 6

技术追求准确,态度积极向上

点击右上角即可分享
微信分享提示