SoFunction
Updated on 2025-03-06

How to end threads elegantly in C#

Everyone knows that in C#, we can use methods to start a thread. When we want to stop the executing thread, we can use methods to force the executing thread to stop, but please note that you are sure that the thread stops immediately after calling the method? The answer is: No!

Let's explain how the Abort method works. Because the common language runtime manages all managed threads, it can also throw exceptions within each thread. The Abort method can throw a ThreadAbortException exception in the target thread, causing the target thread to terminate. However, after the Abort method is called, the target thread may not terminate immediately. Because as long as the target thread is calling unmanaged code and has not returned yet, the thread will not terminate immediately. If the target thread is calling unmanaged code and is trapped in a dead loop, the target thread will not terminate at all. However, this situation is just a special case. More often, the target thread is calling the managed code. Once Abort is called, the thread will terminate immediately.

In fact, when a thread is running, we can read out its state through properties, and the running thread state is. Then if we want to forcefully stop the executing thread, the method will be called, but the method does nothing but throw a ThreadAbortException exception on the thread and set the thread's state to. MSDN's explanation of the AbortRequested state is: the method has been called on the thread, but the thread has not received a pending attempt to terminate it, that is, the thread indicates that it is about to end but has not really ended yet. However, the method sets the thread's state to return immediately, and the state after the thread's real end should be, so be sure to remember to loop through the value of the attribute or call the method to ensure that the terminated thread has really stopped. Only when the attribute is Aborted or the method returns, does it mean that the thread has truly ended.

Next, I will write a sample code to illustrate how to ensure that the code will continue to be executed after the thread is stopped.

var thread = new Thread(  
    new ThreadStart(  
        () =>  
            {  
                while (true)  
                {  
                    //The thread will perform infinite loops and will not end it itself                    (100);  
                }  
            }));  
  
 = true;  
();//Start the thread  
();//Calling the method to try to force terminate the thread  
//The thread thread may not be terminated immediately after calling the method above, so we wrote a loop here to check whether the thread thread has actually stopped.  In fact, you can also use methods here to wait for the thread thread to terminate. The method does the same as the loop we write here, both blocking the main thread until the thread thread terminates.while (!=)  
{  
    //When the Abort method is called, if the state of the thread thread is not Aborted, the main thread will keep looping here until the state of the thread thread becomes Aborted    (100);  
}  
  
// When the above loop jumps out, it means that the thread thread we started has completely terminatedvar thread = new Thread(
    new ThreadStart(
        () =>
            {
                while (true)
                {
                    //The thread will perform infinite loops and will not end it itself                    (100);
                }
            }));

 = true;
();//Start the thread
();//Calling the method to try to force terminate the thread
//The thread thread may not be terminated immediately after calling the method above, so we wrote a loop here to check whether the thread thread has actually stopped.  In fact, you can also use methods here to wait for the thread thread to terminate. The method does the same as the loop we write here, both blocking the main thread until the thread thread terminates.while (!=)
{
    //When the Abort method is called, if the state of the thread thread is not Aborted, the main thread will keep looping here until the state of the thread thread becomes Aborted    (100);
}

//When the loop above jumps out, it means that the thread we startedthreadIt has been completely terminated

However, remember that using methods to terminate the executing thread is not a good method, because the Abort method terminates the thread by throwing exceptions on the thread, which may cause some unexpected problems. The best way is to add a signal to the startup thread. When you want to terminate the thread execution, change the status of the signal. When the startup thread reads that the signal state changes, it ends the execution of the code by itself. This is the safest way.

Set a signal light flag position true, and then wait for the thread to end smoothly:

 = true;           
while (( != ) && ( != ))  
{  
    (10);  
}  
 = true;         
while (( != ) && ( != ))
{
    (10);
}

In the loop of the USBReadThread thread, the detection will be kept as follows:

if (ThreadStopFlg == true) //Judge whether it is time to end the thread{  
    ThreadStopFlg = false;  
    return;  
}  

This is the end of this article about how C# ends a thread elegantly. For more related content on C# ending thread, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!