C # cancellationtokensource terminating thread

Source: Internet
Author: User

We usually use a similar code in multi-threading bool IsExit to control whether the thread runs and terminates, in fact, using CancellationTokenSource to control more useful, we will introduce CancellationTokenSource related usage.

C # uses CancellationTokenSource to terminate threads

Using the CancellationTokenSource object needs to be used in conjunction with the Task object, and the task will control the state of the current run (this does not concern us with how the hole is controlled). The CancellationTokenSource is the external control of the task, such as cancellation and timing cancellation.

Let's take a look at the sample code

  1. class Program
  2. {
  3. //Declare CancellationTokenSource object
  4. static cancellationtokensource canceltokensource = new CancellationTokenSource();
  5. //Program Entry
  6. static void Main(string[] args)
  7. {
  8. Task. Factory. StartNew(mytask, canceltokensource. Token);
  9. Console. WriteLine("Please press ENTER to stop");
  10. Console. ReadLine();
  11. Canceltokensource. Cancel();
  12. Console. WriteLine("stopped");
  13. Console. ReadLine();
  14. }
  15. //test method
  16. static void mytask()
  17. {
  18. //Decide whether to cancel the task
  19. while (! Canceltokensource. iscancellationrequested)
  20. {
  21. Console. WriteLine(DateTime. Now);
  22. Thread. Sleep(+);
  23. }
  24. }
  25. }

Run effect

Task.Factory.StartNew creates and launches the MyTask method, and passes a Cancellationtokensource.token object in. We can suppress the operation of the task by controlling the external CancellationTokenSource object.

When the canceltokensource.iscancellationrequested in the MyTask determines if the task is canceled, it jumps out of the while loop to execute. And it ended the mission.

We can also use the timed cancel task, when a task exceeds the time we set and then automatically cancels the execution of the task. As shown in the following code

    1. var canceltokensource = new CancellationTokenSource(+);

In addition to constructors, we can use a different way to implement timed cancellations, as shown in the following code

    1. Canceltokensource. Cancelafter(+);

The effect is the same, 3 seconds to cancel the timer.

Multiple CancellationTokenSource composite

When there are multiple cancellationtokensource that need to be managed concurrently, such as any one of the tasks canceled, all tasks are canceled. We don't have to go to one to close, just combine the cancellationtokensource that need to be closed together in parallel. As shown in the following code, the execution results are the same as in the above diagram. I will not be anymore.

  1. class Program
  2. {
  3. //Declare CancellationTokenSource object
  4. static cancellationtokensource C1 = new CancellationTokenSource();
  5. static cancellationtokensource c2 = new CancellationTokenSource();
  6. static CancellationTokenSource c3 = new CancellationTokenSource() ;
  7. //Use multiple CancellationTokenSource for composite management
  8. static cancellationtokensource compositecancel = cancellationtokensource. Createlinkedtokensource(C1. Token, C2. Token, c3. Token);
  9. //Program Entry
  10. static void Main(string[] args)
  11. {
  12. Task. Factory. StartNew(mytask, compositecancel. Token);
  13. Console. WriteLine("Please press ENTER to stop");
  14. Console. ReadLine();
  15. //Any one CancellationTokenSource cancel the task, then all tasks will be canceled.
  16. C1. Cancel();
  17. Console. WriteLine("stopped");
  18. Console. ReadLine();
  19. }
  20. //test method
  21. static void mytask()
  22. {
  23. //Decide whether to cancel the task
  24. while (! Compositecancel. iscancellationrequested)
  25. {
  26. Console. WriteLine(DateTime. Now);
  27. Thread. Sleep(+);
  28. }
  29. }
  30. }

The above code calls the c1.Cancel(); trigger MyTask() in the method compositeCancel.IsCancellationRequested to True, then cancels the task. So we judge the CancellationTokenSource object of the compound in all the tasks.

Reprinted from: http://www.wxzzz.com/689.html

C # cancellationtokensource terminating thread

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.