简体   繁体   English

为什么在取消任务之前不等待任务?

[英]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: 所以我期望的行为是:

  • Start the application. 启动应用程序。
  • Start the task (since it's no cancellation request, a delay of 10 seconds will start). 启动任务(由于没有取消请求,因此将延迟10秒)。
  • Wait for 3 seconds and then cancel the token. 等待3秒钟,然后取消令牌。
  • Wait for the task with the 10 second delay to complete and then exit. 等待延迟10秒的任务完成,然后退出。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM