我试图在一个任务的取消象下面
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:
ThrowIfCancellationRequested()
被调用,但令牌不取消呢,所以它不会抛出。
的Thread.Sleep()
被调用,因此运行工作
线程处于休眠状态。
取消()
之称。
IsCanceled
检查。在code。在工作
没有机会认识到,令牌被取消了,所以它仍然在运行,所以 IsCanceled
返回假
。
ThrowIfCancellationRequested()
再次调用,这一次罚球,这实际上取消工作
。
ThrowIfCancellationRequested()
is called, but the token wasn't canceled yet, so it doesn't throw.
Thread.Sleep()
is called, so the thread running the Task
sleeps.
Cancel()
is called.
IsCanceled
is checked. The code in the Task
didn't have a chance to realize that the token was canceled, so it's still running, so IsCanceled
returns false
.
ThrowIfCancellationRequested()
is called again, this time it throws, which actually cancels the Task
.
这就是为什么 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.
相关推荐
最新文章