一任务的取消

编程入门 行业动态 更新时间:2024-10-28 07:29:21
本文介绍了一任务的取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图在一个任务的取消象下面

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.

    更多推荐

    一任务的取消

    本文发布于:2023-11-13 12:26:02,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1584357.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!