首页 > 未分类 > 线程已被中止- “Thread was being aborted”
2019
12-06

线程已被中止- “Thread was being aborted”

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

最后编辑:
作者:搬运工