The C implementation terminates the executing thread

  • 2020-10-07 18:51:47
  • OfStack

This article illustrates the implementation method of C# to terminate the executing thread, and makes an in-depth analysis of some error-prone areas, as follows:

In general, many people use the Abort method to terminate a thread, which is not a good idea! If your thread is operating on a critical resource, it is very likely that the resource will not be released properly and a deadlock problem will occur. The correct approach would be to use the tag to terminate the thread's execution.

The basic idea is to define a variable that describes the "stop" signal and set it to false before the entire program starts. In the thread, the loop determines whether the variable has been set to true, if not, continues execution, otherwise exits the loop and frees the resource, then exits execution. When we need a thread to exit, we simply set the "stop" signal to true.

Now let's look at the specific steps.

First, define a "stop" signal variable:


private volatile bool canStop = false;

Note that we use the volatile keyword here, because the canStop variable will be used by both the calling thread and the thread of execution, that is, initializing and setting its value in the calling thread, and determining its value in the thread of execution. Doing so tells the compiler that the canStop variable will be used by multiple threads, forcing the compiler not to optimize its state. If you are interested, check out MSDN for more explanation of the volatile keyword. canStop is also initialized here.

Now let's look at the code for thread creation and execution:


i = 0;  
//  Use anonymous methods to define the execution body of a thread   
Thread thread = new Thread(  
delegate(object param)  
{  
  //  Wait for the "stop" signal and execute if no signal is received   
  while (!canStop)  
  {  
    i++;  
    UpdateLabel(i);  
  }  
  //  At this point, a stop signal has been received and the resource can be released here   
  //  Initializing variable   
  canStop = false;  
});  
 
thread.Start();

It is very simple to repeatedly determine whether the canStop variable is true in the execution body of the thread. If so, immediately jump out of the while loop (stop the self-adding of the variable and update the interface operation), and then reinitialize the canStop variable as false for the next use.

Hopefully this article has helped you with your C# programming.


Related articles: