线程调用Thread.Abort()方法后,这会给线程注入ThreadAbortException异常,导致线程被终结。该异常可在任何时刻发生并可能彻底摧毁应用程序。另外,使用该技术也不一定总能终止线程,可以通过处理该异常并调用Thread.ResetAbort方法来拒绝被终止。因此并不推荐使用Abort方法来关闭线程。可优先使用一些其他方法,比如提供一个CancellationToken方法来取消线程的执行。
using System;
using System.Threading;
using static System.Console;
using static System.Threading.Thread;
namespace AbortAndResetDemo
{
class Program
{
static void PrintNumbersWithDelay()
{
WriteLine("Starting...");
int i = 1;
Cycle_Print:
try
{
for (; i < 10; i++)
{
Sleep(TimeSpan.FromSeconds(2));
WriteLine(i);
}
}
catch (ThreadAbortException ex)
{
WriteLine($"After Abort, {CurrentThread.Name} state: {CurrentThread.ThreadState}");
Thread.ResetAbort();
WriteLine($"After ResetAbort, {CurrentThread.Name} state: {CurrentThread.ThreadState}");
goto Cycle_Print;
}
}
static void Main(string[] args)
{
WriteLine("Starting program...");
Thread t = new Thread(PrintNumbersWithDelay);
t.Name = "PrintThread";
t.Start();
Sleep(TimeSpan.FromSeconds(6));
t.Abort();
}
}
}
可使用Ctrl+F5直接运行程序,从而避免自动退出程序,看不到程序结果的问题。