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
- class Program
- {
- //Declare CancellationTokenSource object
- static cancellationtokensource canceltokensource = new CancellationTokenSource ();
- //Program Entry
- static void Main(string[] args)
- {
- Task. Factory. StartNew(mytask, canceltokensource. Token);
- Console. WriteLine("Please press ENTER to stop");
- Console. ReadLine();
- Canceltokensource. Cancel();//Notify Cancel task or terminate thread
- Console. WriteLine("stopped");
- Console. ReadLine();
- }
- //test method
- static void mytask()
- {
- //Decide whether to cancel the task
- while (! Canceltokensource. iscancellationrequested)
- {
- Console. WriteLine(DateTime. Now);
- Thread. Sleep(+);
- }
- }
- }
Cancellation of timeout tasks via CancellationTokenSource in. Net 4.5
We typically use CancellationTokenSource to implement task cancellation during task-based tasks, starting with a simple example.
();
. Factory.startnew (() =
{
(!canceltokensource.iscancellationrequested)
{
. Now);
. Sleep (1000);
}
}, Canceltokensource.token);
);
. ReadLine ();
Canceltokensource.cancel ();
);
. ReadLine ();
Many times, in addition to the manual cancellation as in the example above, we tend to set an expected execution time on the task, and automatically cancel the timeout task. The usual practice is to start a new timer and execute the Cancellationtokensource.cancel method in the timer's timeout callback. In. Net 4.5, this is further simplified, and we can do this by setting timeouts when creating CancellationTokenSource.
var canceltokensource = new CancellationTokenSource (3000);
In addition, the same effect can be achieved with the following code.
Canceltokensource.cancelafter (3000);
C # CancellationTokenSource terminating thread CancellationTokenSource implementation of cancellation of timeout task