157 recommendations for writing high-quality code to improve C # programs--Recommendation 77: correctly stopping threads

Source: Internet
Author: User

Recommendation 77: Properly stop threads

Developers always try to have more control over their own code. For example, "let the thread that is still working immediately stop." However, it is not what we want to do, it involves at least two questions.

The first problem is that, just as a thread does not start immediately, the thread does not stop. Regardless of the way in which the worker thread needs to be stopped, the worker is busy with the most urgent work at hand and exits when it feels right. As an example of the most traditional Thread.Abort method, if the thread is currently executing a piece of unmanaged code, the CLR will not throw ThreadAbortException and will only throw ThreadAbortException if the code continues to return to the CLR. Of course, even in a CLR environment, ThreadAbortException is not immediately raised.

The second problem is to properly stop the thread, not in what behavior the caller has taken (such as the first Thread.Abort () method), but more on whether the worker thread can proactively respond to the caller's stop request. The general mechanism is that if the thread needs to be stopped, then the thread itself should be responsible for opening such an interface to the caller: cancled. Thread at work at the same time, but also to a certain frequency detection cancled identity, if detected cancled, the thread itself will be responsible for the exit.

The FCL now provides us with a standard cancellation mode: Cooperative cancellation (cooperative cancellation). The mechanism for collaborative cancellation is the one mentioned in the second question above. The following is an example of the most basic collaborative cancellation:

CancellationTokenSource cts =NewCancellationTokenSource (); Thread T=NewThread (() =    {           while(true)          {              if(CTS. token.iscancellationrequested) {Console.WriteLine ("thread is terminated! ");  Break;              } Console.WriteLine (DateTime.Now.ToString ()); Thread.Sleep ( +);  }      });  T.start ();  Console.ReadLine (); Cts. Cancel (); 


The caller uses the Cancel method of CancellationTokenSource to notify the worker to exit. The worker thread is working at about 1000ms, checking for an external cancel signal, and exiting if there is such a signal. As you can see, the thread itself actually plays a major role in the mechanism of properly stopping threads. The work code in the example is simple but sufficient to illustrate the problem. More complex computational work should also be done in such a way as to properly and correctly handle the exit.

The key type in collaborative cancellation is CancellationTokenSource. It has a key property Token,token is a value type named CancellationToken. CancellationToken then further provides the Boolean property iscancellationrequested as the identity that needs to be canceled. CancellationToken There is one more way to pay attention, which is the Register method. It is responsible for passing an action delegate, which is invoked when the thread is stopped, using the following method:

Cts. Token.register (() ={      Console.WriteLine (" worker thread was terminated. ");  


This example uses thread to demonstrate, and if using ThreadPool is the same pattern, here is not to repeat. Later, you'll talk about task tasks, which depend on CancellationTokenSource and CancellationToken to complete all the cancellation controls.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--Recommendation 77: correctly stopping threads

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.