取消令牌的使用

我正在尝试学习如何使用取消令牌取消任务。 在这里,我已经为它编写了一个UnitTest,但我没有得到它的工作方式。

[TestMethod] public async Task Task_should_not_run_when_token_cancelled_before_its_call() { var cts = new CancellationTokenSource(); var token = cts.Token; cts.Cancel(); Debug.WriteLine("Calling Cancellable Method".ToUpper()); try { await CheckMeCalled(token); } catch (Exception expException) { } } private async Task CheckMeCalled(CancellationToken ct) { Debug.WriteLine("Before task delayed".ToUpper()); await Task.Delay(5000); Debug.WriteLine("After task delayed".ToUpper()); } 

在上面的测试中,我在调用CheckMeCalled方法之前调用了CheckMeCalled cts.Cancel() 。 所以不应该取消它。 但它正在全力以赴。

我已经读到了某个地方

If Task is not running and you cancel it then it will not go to a running state instead it go for canceled state when you call it

但这似乎并没有发生在这里。 有人可以向我解释一下吗? 任何帮助表示赞赏。 欢呼:)

您添加的引用与通过Task.RunTask.Factory.Startnew创建新Task Task.Factory.Startnew 。 将CancellationToken传递给方法时,必须在运行之前主动检查令牌

 private async Task CheckMeCalled(CancellationToken ct) { ct.ThrowIfCancellationRequested(); Debug.WriteLine("Before task delayed".ToUpper()); await Task.Delay(5000, ct); Debug.WriteLine("After task delayed".ToUpper()); } 

以下是Stephan Toub关于取消令牌和Task的引用:

如果令牌在任务开始执行之前已请求取消,则任务将不会执行。 它不会转换为Running,而是立即转换为Canceled。 这样可以避免运行任务的成本,如果它在运行时只是被取消。

我还建议阅读NET 4取消框架,以便PFX团队对取消机制进行广泛的审查

您必须手动检查令牌以查看是否请求取消。

附:

 ct.IsCancellationRequested