Recently, when the project was coming to an end, an incredible bug occurred. It took two hours to determine that the bug was caused by multithreading and encountered the issue of thread nesting.
Thread nesting means that the Execution Code of thread A starts thread B, and the Execution Code of thread B starts thread C.
I originally thought that after thread A is Abort, thread B will be automatically Abort, but I am wrong.
In this scenario, thread management is very important.
After thread A is Abort, thread B will not be Abort by its parent thread unless you force it to Abort thread B in thread.
After thread A receives the Abort command (catch (ThreadAbortException), Abort thread B.
Of course, if you do not want to avoid Abort thread B after thread A is Abort, you can also choose not Abort thread B. But in this way, thread B is stocked and not controlled.
The following is an example:
T1 start thread t2, t2 start t3.
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;namespace InnerThread{ class Program { static void Main(string[] args) { Thread t1 = new Thread(new ThreadStart(DoWork1)); t1.Name = "T1"; t1.Start(); Thread.Sleep(5000); t1.Abort(); Console.ReadKey(); } static void DoWork1() { Thread t2 = null; try { t2 = new Thread(new ThreadStart(DoWork2)); t2.Name = "T2"; t2.Start(); while (true) { Console.WriteLine("t1 is working"); Thread.Sleep(500); } } catch (ThreadAbortException) { Console.WriteLine("t1 has been abort."); t2.Abort(); } catch(Exception ex) { Console.WriteLine(ex.Message); } } static void DoWork2() { Thread t3 = null; try { t3 = new Thread(new ThreadStart(DoWork3)); t3.Name = "T3"; t3.Start(); while (true) { Console.WriteLine("t2 is working"); Thread.Sleep(500); } } catch (ThreadAbortException) { Console.WriteLine("t2 has been abort."); t3.Abort(); } } static void DoWork3() { try { while (true) { Console.WriteLine("t3 is working"); Thread.Sleep(500); } } catch (ThreadAbortException) { Console.WriteLine("t3 has been abort."); } } }}
The execution result is as follows:
After t1 is Abort, call t2's Abort, t2 is Abort ,...........
Multithreading with caution...