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