我想使用 CancellationTokenSource 停止任务。我的测试如下:
测试 1:使用 Cancel() 成功停止了任务。
测试 2:使用 CancelAfter() 没有停止任务,为什么?
任务动作是:
static Action testFun = () => {
Thread.Sleep(4000); // or other a long time operation
Console.WriteLine("Action is end");
};
Run Code Online (Sandbox Code Playgroud)
测试1代码:
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();
Run Code Online (Sandbox Code Playgroud)
输出是:
Task is canceled
Run Code Online (Sandbox Code Playgroud)
测试2代码:
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
//Register the cancel action
token.Register(() …Run Code Online (Sandbox Code Playgroud)