C#:父线程触发异常后如何中断子线程的循环?
父线程触发异常后中断子线程循环的实现方案
针对你给出的代码场景,父线程被调用Interrupt()进入catch块后,可通过以下两种可靠方式中断子线程的循环:
方法一:使用Thread.Interrupt()配合子线程中断检查
通过在父线程的catch块中调用子线程的Interrupt()方法,同时在子线程中加入中断响应逻辑:
Thread child; Thread parent = new Thread(() => { child = new Thread(() => { try { for (int i = 0; i < int.MaxValue; i++) { Console.WriteLine("THREAD 1 = " + i); // 加入可中断操作,让线程有机会响应中断请求 Thread.Sleep(1); // 主动检查中断状态,触发则退出循环 if (Thread.CurrentThread.InterruptRequested) { Console.WriteLine("子线程收到中断请求,退出循环"); break; } } } catch (ThreadInterruptedException) { Console.WriteLine("子线程被中断,退出循环"); } }); child.Start(); try { child.Join(); } catch (Exception ex) { System.Console.WriteLine(ex.ToString()); // 向子线程发送中断请求 child.Interrupt(); } }); parent.Start(); parent.Interrupt();
说明
Thread.Interrupt()会在子线程处于WaitSleepJoin状态时抛出ThreadInterruptedException,因此子线程中需要包含Thread.Sleep这类会让线程进入等待状态的操作;- 也可以主动检查
Thread.CurrentThread.InterruptRequested状态,直接退出循环,避免依赖异常捕获。
方法二:使用CancellationToken(推荐)
这是.NET中更安全可控的线程取消方案,通过取消令牌通知子线程退出循环:
CancellationTokenSource cts = new CancellationTokenSource(); Thread child; Thread parent = new Thread(() => { child = new Thread(() => { for (int i = 0; i < int.MaxValue; i++) { // 检查取消令牌,若已触发则退出循环 if (cts.Token.IsCancellationRequested) { Console.WriteLine("子线程收到取消请求,退出循环"); break; } Console.WriteLine("THREAD 1 = " + i); } }); child.Start(); try { child.Join(); } catch (Exception ex) { System.Console.WriteLine(ex.ToString()); // 触发取消令牌,通知子线程终止 cts.Cancel(); } }); parent.Start(); parent.Interrupt();
说明
- 子线程在循环中主动检查
CancellationToken的状态,无需依赖线程状态或异常; - 这种方式逻辑清晰,避免了
Thread.Interrupt的状态依赖问题,也不会像过时的Thread.Abort()那样导致资源泄漏或数据不一致。
内容的提问来源于stack exchange,提问作者José Robson Assis
相关产品推荐
相关产品推荐

