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

异常信息摘要:

Unhandled Exception:Thread was being aborted.

 

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

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

 

备注:

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

相关文章: