特殊的Exception : ThreadAbortException
using System;
using System.Threading;
using System.Security.Permissions;
namespace ThreadAbortTest
{
public class ThreadWork
{
public static void DoWork()
{
try
{
DoWorkInternal();
}
catch(ThreadAbortException e)
{
Console.WriteLine(\"Exception In Dowork(): {0}\", e.Message);
//Thread.ResetAbort();
}
finally
{
Console.WriteLine(\"Dowork() is dying\");
}
}
public static void DoWorkInternal()
{
try
{
for(int i=0; i<10000; i++)
{
Console.WriteLine(\"DoWorkInternal - working.\");
Thread.Sleep(100);
}
}
catch(ThreadAbortException e)
{
Console.WriteLine(\"Exception In DoWorkInternal(): {0}\", e.Message);
//Thread.ResetAbort();
}
finally
{
Console.WriteLine(\"DoWorkInternal() ending\");
}
}
}
class ThreadAbortTest
{
public static void Main()
{
Thread myThread = new Thread(new ThreadStart(ThreadWork.DoWork));
myThread.Start();
Thread.Sleep(1000);
myThread.Abort();
myThread.Join();
Console.WriteLine(\"Main ending.\");
}
}
}
显示
DoWorkInternal - working.
…
DoWorkInternal - working.
Exception In DoWorkInternal(): Thread was being aborted.
DoWorkInternal() ending
Exception In Dowork(): Thread was being aborted.
Dowork() is ending
Main ending.
1.ThreadAbortException 在DoWorkInternal中被catch了,DoWork中依然可以catch到.
显然,MS希望Thread.Abort调用时,调用栈中每个函数都知道.
2.去掉所有的try-catch,程序照常执行. VS的Debug-Exception设定对话框中,打开所有的
exception,可看到ThreadAbortException 是一个特殊的exception.
3. myThread.Abort(); myThread.Join(); //等待myThread的finally块的执行
