关于ThreadAbortExcption异常处理

 

之前程序中,使用Thread.Abort()方法来终止线程的运行,但它是抛出ThreadAbortException异常来终止线程。

异常信息摘要:

Unhandled Exception:Thread was being aborted.

 

但此时,不想抛出此异常而使用线程终止,就使用了catch方式来捕获此异常,但即使捕获异常之后,程序还是会报ThreadAbortException异常。

最后终于在 http://msdn.microsoft.com/zh-cn/library/system.threading.threadabortexception.aspx 中找到了合理的解释。

 

备注:

在调用 Abort 方法以销毁线程时,公共语言运行时将引发 ThreadAbortException。 ThreadAbortException 是一种可捕获的特殊异常,但在 catch 块的结尾处它将自动被再次引发。 引发此异常时,运行时将在结束线程前执行所有 finally 块。 由于线程可以在 finally 块中执行未绑定计算或调用 Thread.ResetAbort 来取消中止,所以不能保证线程将完全结束。 如果您希望一直等到被中止的线程结束,可以调用 Thread.Join 方法。 Join 是一个阻塞调用,它直到线程实际停止执行时才返回。

 


处理方式是在catch到ThreadAbortException异常后,使用Thread.ResetAbort()来取消中止。

 

下面是MSDN上的代码示例:

 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 }
View Code

 

执行结果:

 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 @ 2014-08-21 13:04  闫晓盼  阅读(988)  评论(0编辑  收藏  举报