取消任务 [英] Canceling a task

查看:157
本文介绍了取消任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我需要取消,如果等待时间超过一个任务。例如

I have a task which i need to cancel if the wait time is over. For instance

var t = Task.Factory.StartNew(() => 
{
  Thread.Sleep(5000) // some long running task
  "do something"
});
Task.WaitAll(new[] {t}, 1000);



不过好像任务仍然继续工作。我试着用CancellationTokenSource但没有似乎正常工作。

But it seems the task still keeps working. I tried using CancellationTokenSource but that didnt seem to work as well.

我证实了这一点使用下面的代码片段

I confirmed this using the following snippet

static void Main(string[] args)
        {
            var cancellationTokenSource = new CancellationTokenSource();

            var t = Task.Factory.StartNew(() => {
                Thread.Sleep(5000);
                Console.WriteLine("Still working");
            }, cancellationTokenSource.Token);

            Task.WaitAll(new[] {t}, 1000);

            cancellationTokenSource.Cancel();

            Console.ReadLine();
        }



控制台显示仍在工作。我以为任务将被取消。

Console displays "Still working". I thought the task would have been cancelled.

我相信我失去了一些东西。我在想什么?谢谢你。

I am sure I am missing something. What am i missing? Thanks.

推荐答案

取消标记不神奇取消任何东西。他们只是允许的你以一种标准的方式,例如检查取消通过 ThrowIfCancellationRequested

Cancellation tokens don't magically cancel anything. They just allow you to check for cancellation in a standardized way, e.g. via ThrowIfCancellationRequested.

所以通常你有一些任务,需要进行大量的工作。它会定期调用 ThrowIfCancellationRequested ,然后它需要取消任务中的任何代码调用的 取消 上时,它需要 CancellationTokenSource 。该任务将抛出时,注销接下来的检查,一切都会好起来。

So typically you'd have some task which needs to perform a lot of work. It periodically calls ThrowIfCancellationRequested, and then any code which needs to cancel the task will call Cancel on the CancellationTokenSource when it needs to. The task will throw when it next checks for cancellation, and all will be well.

这听起来像你正在寻找一个非合作取消 - 这将是危险的,正是同样的原因,正常 Thread.Abort的是危险的。它的清洁,让任务在挑选它会允许自己被取消了分。

It sounds like you're looking for a non-cooperative cancellation - and that would be dangerous, for exactly the same reasons that the normal Thread.Abort is dangerous. It's cleaner to let the task pick the points at which it will allow itself to be cancelled.

这篇关于取消任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆