我试图在一个任务的取消象下面
I tried to run a simple example on the cancellation of a task like the one below
CancellationTokenSource tokenSource2 = new CancellationTokenSource(); CancellationToken token2 = tokenSource2.Token; Task task2 = new Task(() => { for (int i = 0; i < int.MaxValue; i++) { token2.ThrowIfCancellationRequested(); Thread.Sleep(100); Console.WriteLine("Task 2 - Int value {0}", i); } }, token2); task2.Start(); Console.WriteLine("Press any key to cancel the task"); Console.ReadLine(); tokenSource2.Cancel(); Console.WriteLine("Task 2 cancelled? {0}", task2.IsCanceled);
我预计 Console.WriteLine(任务2取消{0}?,task2.IsCanceled); 将打印 **任务2取消了?真正的** ,但它印的假
I expected that Console.WriteLine("Task 2 cancelled? {0}", task2.IsCanceled); would print **"Task 2 cancelled? True"**, but it printed "False".
你知道发生了什么事?那是预期的行为?谢谢你。
Do you know what happened? Is that the expected behaviour? Thanks.
编辑:保证任务未完成取消请求调用之前。我加了到Console.ReadLine()。
to ensure that the task hasn't completed before the cancellation request is called. I added the Console.ReadLine().
推荐答案首先,也许你误解了 IsCanceled 意味着什么?这并不意味着这个工作正在等待取消,所以应该很快完成,就意味着这个工作已被取消,现在是完整的。
First, maybe you misunderstand what IsCanceled means? It doesn't mean "this Task is pending cancellation, so it should complete shortly", it means "this Task has been canceled, it is now complete".
如果你没有误会,想想事件完全相同的顺序。什么情况是这样的:
If you didn't misunderstand that, think about what exactly the sequence of events is. What happens is this:
这就是为什么 ISCanceled 将返回假给你。如果你希望它返回真,您可以添加类似 Thread.sleep代码(150)前检查 IsCanceled ,或者甚至更好,实际上等待工作来完成。
This is why ISCanceled is returning false to you. If you want it to return true, you could add something like Thread.Sleep(150) before checking IsCanceled, or, even better, actually wait for the Task to complete.
更多推荐
一任务的取消
发布评论