因此,根据对这个职位的回答:
2)如果任务的主体也监视取消令牌并抛出包含该令牌的OperationCanceledException (这就是ThrowIfCancellationRequested所做的),那么当任务看到该OCE时,它会检查OCE的令牌是否与任务的令牌匹配。如果是这样,则将该异常视为对协作取消和任务过渡到已取消状态(而不是错误状态)的确认。
由此我了解到,通过将令牌传递给任务的构造函数,然后调用该令牌的ThrowIfCancellationRequested()方法,任务实际上将和平终止,而不必显式地捕获OperationCanceledException。
然而,事实证明,有一个例外被抛出,所以我相信我可能误解了机修工。
我的代码:
public void AI()
{
IsBusy = true;
var token = stopGameCancellationTokenSource.Token;
var workTask = new Task(() => aiWork(token), token);
workTask.Start();
workTask.ContinueWith(task => { IsBusy = false; });
}
private void aiWork(CancellationToken token)
{
while ( true)
{
//Some computation being done here
token.ThrowIfCancellationRequested(); //Exception is thrown here, I thought it wouldn't
//More computation here, which I don't want to happen if cancellation has benn requested
}
}发布于 2015-04-21 15:19:48
这条线
token.ThrowIfCancellationRequested();显式抛出异常。链接告诉您的是,如果任务的令牌与刚才抛出的OperationCanceledException中的令牌匹配,“任务将转换到已取消的状态(而不是错误状态)”。
因此,底线是,如果您不希望在任务被取消时抛出异常,只需省略这一行!
发布于 2015-04-21 15:31:36
除了在@JurgenCamilleri 回答 of 中解释为什么要得到错误之外,您可能要做的是循环直到请求取消为止。您可以通过将代码更改为如下内容来做到这一点:
private void aiWork(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
//Some computation being done here
if (token.IsCancellationRequested)
break; // need to cancel
//More computation here, which I don't want to happen if cancellation has been requested
}
} 发布于 2015-04-21 15:32:29
正如该方法的名称所示,如果请求取消,ThrowIfCancellationRequested将引发异常(OperationCanceledException)。
如果您真的不希望抛出异常,可以检查token.IsCancellationRequested是否为真,在本例中,退出函数。但是,除非你有充分的理由不这么做,否则我会重新考虑继续使用token.ThrowIfCancellationRequested()。
https://stackoverflow.com/questions/29776231
复制相似问题