I want to use CancellationTokenSource stop the Task. My tests as follow:
Test 1 : Using Cancel() stopped the task sucessfully.
Test 2 : Using CancelAfter() did not stop the task, Why?
The task action is:
static Action testFun = () => {
Thread.Sleep(4000); // or other a long time operation
Console.WriteLine("Action is end");
};
The test1 code:
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
//Register the cancel action
token.Register(() =>
{
Console.WriteLine("Task is canceled");
});
Task task = new Task(testFun, token);
task.Start();
source.Cancel();
Console.ReadLine();
Output is:
Task is canceled
Test2 Code:
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
//Register the cancel action
token.Register(() =>
{
Console.WriteLine("Task is canceled");
});
Task task = new Task(testFun, token);
task.Start();
source.CancelAfter(100); // the time 100ms < the task 4000ms
Console.ReadLine();
Output is:
Task is canceled
Action is end
My question is why task is still running when CancelAfter()
is invoked on CancellationTokenSource
How do I revise the test2 ? Thank you.