特殊的Exception : ThreadAbortException
Post by "aloneplayer", 2006-10-12, 14:29-----------------------------------------------------
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块的执行
Reply by "SmiletotheLife", 2006-10-12, 17:18
-----------------------------------------------------
如果Catch了ThreadAbortException,辅线程仍然存在;反之则消失。
Reply by "J2.NETe", 2006-10-14, 9:29
-----------------------------------------------------
确实是个不错的东西。
看了MSDN,甚至可以用ExceptionState来向被Abort的Thread传递信息。
但有个问题:
Runtime或者.NET Framework是如何让Catch之后的ThreadAbortException在Catch块之后再次Rethrow的?
页:
[1]