The thread is disabled correctly. Recommendation..., thread close recommendation
When I was working on a project recently, I was confused by multiple threads, and my mind was almost broken down. One problem was found during single-step debugging. Sometimes the abort method of the thread cannot jump to the exception handling of the exception ThreadAbortException as expected, and then the thread is closed smoothly.
Find a solution in the book, and share it here, so that you will forget it in the future.
First, the thread does not stop when it is stopped, just as it cannot start immediately. No matter how it notifies the thread to stop, the worker thread will finish the current task and exit at the right time, take Thread. the power of the Abort method. If the thread is currently executing an unmanaged code, ThreadAbortException will be triggered only when the code is returned to the CLR. note that ThreadAbortException does not occur immediately even in the CLR environment.
In addition, to stop the thread correctly, the caller should not take any action, but be more dependent on whether the worker thread can actively respond to the caller's stop request.
FCL provides a standard cancellation mode: Collaborative cancellation. Its mechanism is: if the thread needs to be stopped, the thread itself opens the interface: Cancelled. While the thread is working, it will also detect the Cancelled mark at a certain frequency. If it detects it, the thread will be responsible for exiting.
The following sample code is provided.
CancellationTokenSource cts=new CancellationTokenSource();Thread t=new Thread(()=> { while(true) { if(cts.Token.IsCancellationRequested) { Console.WriteLine("Thread has been stopped"); break; } Thread.Sleep(1000); } });t.Start();Console.ReadLine();cts.Cancel();
The caller uses the CancellationTokenSource Cancel Method to notify the worker thread to exit. The working thread operates at a frequency of about ms while detecting whether there is an external Cancel signal. If yes, It exits. We can see that in the mechanism of correctly stopping a thread, the thread itself is actually playing a role. Among them, CancellationTokenSource has a key attribute Token, which belongs to a value type named CancellationToken. This type provides a Boolean identifier IsCancellationRequested as the identifier for canceling a job.