[英]Why isn't a Task awaited before it get's cancelled?
I need to write a service with some complex behaviour like simultanious tasks and I'm facing an issue with. 我需要编写具有某些复杂行为(如同时执行的任务)的服务,但现在遇到了问题。
I've written a sample in xUnit to show you the problem. 我在xUnit中编写了一个示例来向您展示问题。
1 want to execute a task on a background, eventually start some child tasks. 1要在后台执行任务,最终启动一些子任务。 At a moment in time the task needs to be cancelled.
此时需要取消任务。
Therefore, I have the following in place: 因此,我有以下几点:
[Fact]
public void ShouldWaitUnitTaskCompleted()
{
Task.Factory.StartNew(() =>
{
while (!cancellationTokenSource.IsCancellationRequested)
{
Task.Delay(10000).Wait();
TaskIsCompleted = true;
}
}, cancellationTokenSource.Token);
Thread.Sleep(3000);
cancellationTokenSource.Cancel();
Assert.True(TaskIsCompleted);
}
} }
However, the xUnit completes after 3 seconds (my thread sleep). 但是,xUnit在3秒钟后完成(我的线程处于休眠状态)。 In my task, I'm having a loop that say, as long as it's not a cancellation request delay if for 10 second.
在我的任务中,我有一个循环,说,只要不是10秒的取消请求延迟。
So the behaviour I expect would be: 所以我期望的行为是:
Why doesn't my code wait for the 10 seconds frame to pass? 为什么我的代码不等待10秒帧通过?
You don't await
your Task
which you create. 您不必
await
创建的Task
。 Hence the execution of the code just continues on to the Thread.Sleep(3000)
. 因此,代码的执行仅继续到
Thread.Sleep(3000)
。
Cancel
signals that cancellation has been requested. Cancel
表示已请求取消。
It doesn't wait for all tasks to complete before allowing the cancelling code to carry on doing useful things - if you do want to wait for those tasks to respond, there are already mechanisms for you to do this, separately. 在允许取消代码继续做有用的事情之前,它不会等待所有任务完成-如果您确实想等待这些任务响应,则已经有单独的机制可以这样做。 So
Cancel
just does one job, and does it well. 因此,
Cancel
仅能完成一项工作,而且做得很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.