Asynchronous and parallel ~ The role of CancellationTokenSource on the thread,

Source: Internet
Author: User

Asynchronous and parallel ~ The role of CancellationTokenSource on the thread,

Returned directory

Speaking of CancellationTokenSource, we should not be unfamiliar. For Thread and Task, we start a Thread to do something. If we want it to stop passively at a certain stage, we can use this CancellationTokenSource object, inject it into the Task. When the Cancel () method is triggered by the outside world, your thread will be canceled, which is quite useful, it seems that it is a method encapsulated in the Task to return to the weekly mechanism and control the Task status externally!

Check uncle's test code

CancellationTokenSource cancelTokenSource = new CancellationTokenSource (); Task. Run () => {while (! CancelTokenSource. isCancellationRequested) {Console. writeLine (DateTime. now); Thread. sleep (5000) ;}}, cancelTokenSource. token); Console. writeLine ("cancel this task by pressing the task key"); Console. readLine (); cancelTokenSource. cancel (); Console. writeLine ("STOPPED"); Console. readLine ();

Running result

Through Microsoft's encapsulation of tasks, we have some references. When designing a framework, if you want to leave an interface for the outside world, you can use method callback.

Thank you for reading this article!

Thank you!

Returned directory

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.