时间:2022-11-02 10:59:47 | 栏目:.NET代码 | 点击:次
Abort方法可以通过跑出ThreadAbortException异常中止线程,而使用ResetAbort方法可以取消中止线程的操作,下面通过代码演示使用 ResetAbort方法。
class Program
{
static void Main(string[] args)
{
Thread thread = new Thread(ThreadMethod); //执行的必须是无返回值的方法
thread.Name = "子線程A";
thread.Start();
Console.ReadKey();
}
public static void ThreadMethod(object parameter)
{
try
{
Console.WriteLine("我是:{0},我要終止了!", Thread.CurrentThread.Name);
//开始终止线程
Thread.CurrentThread.Abort();
//下面的代码不会执行
for (int i = 0; i < 10; i++)
{
Console.WriteLine("我是:{0},我循環{1}次", Thread.CurrentThread.Name, i);
}
}
catch (ThreadAbortException ex)
{
Console.WriteLine("我是:{0},我又恢復了", Thread.CurrentThread.Name);
//恢复被终止的线程
Thread.ResetAbort();
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine("我是:{0},我循環{1}次", Thread.CurrentThread.Name, i);
}
}
}
