- Abort方法和Interrupt都是用来终止线程的,但是两者还是有区别的。
1、他们抛出的异常不一样,Abort 方法抛出的异常是ThreadAbortException, Interrupt抛出的异常为ThreadInterruptedException
2、调用interrupt方法的线程之后可以被唤醒,然而调用Abort方法的线程就直接被终止不能被唤醒的。
using System;
using System.Threading;
namespace ThreadPoolOne
{
class Program
{
static void Main(string[] args)
{
Thread abortThread = new Thread(AbortMethod);
abortThread.Name = "Abort Thread";
abortThread.Start();
Thread.Sleep(1000);
try
{
abortThread.Abort();
}
catch
{
Console.WriteLine("{0} Exception happen in Main Thread", Thread.CurrentThread.Name);
Console.WriteLine("{0} Status is:{1} In Main Thread ", Thread.CurrentThread.Name, Thread.CurrentThread.ThreadState);
}
finally
{
Console.WriteLine("{0} Status is:{1} In Main Thread ", abortThread.Name, abortThread.ThreadState);
}
abortThread.Join();
Console.WriteLine("{0} Status is:{1} ", abortThread.Name, abortThread.ThreadState);
Console.Read();
}
private static void AbortMethod()
{
try
{
Thread.Sleep(2000);
}
catch (Exception e)
{
Console.WriteLine(e.GetType().Name);
Console.WriteLine("{0} Exception happen In Abort Thread", Thread.CurrentThread.Name);
Console.WriteLine("{0} Status is:{1} In Abort Thread ", Thread.CurrentThread.Name, Thread.CurrentThread.ThreadState);
}
finally
{
Console.WriteLine("{0} Status is:{1} In Abort Thread", Thread.CurrentThread.Name, Thread.CurrentThread.ThreadState);
}
}
}
}