如何取消CancellationToken [英] How to cancel a CancellationToken

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

问题描述

我启动一个任务,然后启动其他任务,依此类推。

鉴于该树,如果任何任务失败,则整个操作的结果将是无用的。我正在考虑使用取消令牌。令我惊讶的是,令牌没有 CancelThisToken()方法...

I start a task, that start other tasks and so forth.
Given that tree, if any task fails the result of the whole operation is useless. I'm considering using cancellation tokens. To my surprise, the token does not have a "CancelThisToken()" method...

所以我的问题是:我怎么能拥有 一个 CancellationToken ,取消它?

So my question is: how can I, in possession of ONLY a CancellationToken, cancel it?

推荐答案

文档状态说明您需要从源对象调用cancel方法。您提供的链接中包含示例代码。以下是相关部分:

As the docs state you need to call the cancel method from the source object. Example code is included in the link you provided. Here are the relevant sections:

// Define the cancellation token.
CancellationTokenSource source = new CancellationTokenSource();
previouslyProvidedToken = source.Token;
...
source.Cancel();

CancellationToken Struct


如何我只能拥有一个CancellationToken才能取消它吗?

how can I, in possession of ONLY a CancellationToken, cancel it?

如果没有引用来源,您就不能取消令牌。这并不意味着您需要首先生成令牌的 CancellationTokenSource 。给定 CancellationToken 后,您可以创建一个新的令牌源实例,将其令牌分配给提供的令牌并取消。可以读取此令牌的所有其他方将看到已请求取消令牌。

Without a reference to the source you cannot cancel a token. That doesn't mean that you need the CancellationTokenSource that first spawned the token. When given a CancellationToken, you can create a new instance of token source assign it's token to the provided token and cancel it. All other parties that can read this token will see that it's cancellation has been requested.

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

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