继续执行已取消的任务 [英] ContinueWith a cancelled Task
问题描述
我已经定义了以下任务
var t = Task.Factory.StartNew(
() => LongRunningMethod( cancellationToken ),
cancellationToken
);
t.ContinueWith(
Callback,
cancellationToken,
TaskContinuationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext()
);
在LongRunningMethod
内,我检查取消令牌是否请求取消,如果是,则从方法中返回.这样很好.
Inside the LongRunningMethod
, I check if the cancellation token has a cancellation requested, and if so, I return from the method. That much works fine.
但是,在这种情况下不会调用Callback.如果我将上面的第二行替换为
However, the Callback does not get called in this scenario. The callback does get called if I replace the second line above with
t.ContinueWith(
x => Callback( x, cancellationToken ),
TaskScheduler.FromCurrentSynchronizationContext()
);
在这种情况下,任务仍然认为它已完成.
In this situation, the task still thinks it ran to completion.
为什么第一次通话不起作用?我的印象是TaskContinuationOptions.None
意味着无论线程的状态如何,都会调用回调.
Why doesn't the first call work? I was under the impression that TaskContinuationOptions.None
means that the callback will get called regardless of the state of the thread.
我要通过以下方式取消任务:
I am cancelling the Task by calling:
_cancellationTokenSource.Cancel();
在某种程度上相关的注释中,不得不传递取消令牌似乎是Task库的主要设计缺陷.
On a somewhat related note, having to pass around cancellation tokens seems like a major design flaw of the Task library.
推荐答案
您的继续任务需要您取消的CancellationToken.这意味着继续任务在未启动时就被取消了.不要将该令牌传递给您不想取消的事物.
Your continuation task takes a CancellationToken which you cancel. This means that the continuation task, while unstarted, is being cancelled. Don't pass that token to thing which you don't want to cancel.
CancellationToken旨在立即取消整个动作图.您可以通过不传递令牌来取消取消交易.
CancellationToken is meant to cancel the whole graph of actions at once. You can exclude stuff from cancellation by not passing the token.
这篇关于继续执行已取消的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!