关于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上的代码示例:

 using System;
using System.Threading;
using System.Security.Permissions; public class ThreadWork {
public static void DoWork() {
try {
for(int i=; i<; i++) {
Console.WriteLine("Thread - working.");
Thread.Sleep();
}
}
catch(ThreadAbortException e) {
Console.WriteLine("Thread - caught ThreadAbortException - resetting.");
Console.WriteLine("Exception message: {0}", e.Message);
Thread.ResetAbort();
}
Console.WriteLine("Thread - still alive and working.");
Thread.Sleep();
Console.WriteLine("Thread - finished working.");
}
} class ThreadAbortTest {
public static void Main() {
ThreadStart myThreadDelegate = new ThreadStart(ThreadWork.DoWork);
Thread myThread = new Thread(myThreadDelegate);
myThread.Start();
Thread.Sleep();
Console.WriteLine("Main - aborting my thread.");
myThread.Abort();
myThread.Join();
Console.WriteLine("Main ending.");
}
}

执行结果:

 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.
上一篇:Protobuf的简单介绍、使用和分析


下一篇:Android学习(三)