如何取消CancellationToken

编程入门 行业动态 更新时间:2024-10-26 20:23:13
本文介绍了如何取消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

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

发布评论

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

>www.elefans.com

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