获取任务CancellationToken

编程入门 行业动态 更新时间:2024-10-26 14:40:39
本文介绍了获取任务CancellationToken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我能否获得在执行任务操作期间传递给Task构造函数的CancellationToken.大多数示例如下:

Can I get CancellationToken which was passed to Task constructor during task action executing. Most of samples look like this:

CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; Task myTask = Task.Factory.StartNew(() => { for (...) { token.ThrowIfCancellationRequested(); // Body of for loop. } }, token);

但是,如果我的动作不是lambda而是放置在其他类中的方法并且我没有直接访问token怎么办?唯一的方法就是将token作为状态传递?

But what if my action is not lambda but a method placed in other class and I don't have direct access to token? Is the only way is to pass token as state?

推荐答案

但是,如果我的动作不是lambda而是放置在其他类中的方法并且我没有直接访问令牌的权限,该怎么办?唯一的方法是将令牌作为状态传递吗?

But what if my action is not lambda but a method placed in other class and I don't have direct access to token? Is the only way is to pass token as state?

是的,在这种情况下,您需要传递装在框内的令牌作为状态,或包含在其他用作状态的类型中.

Yes, in that case, you would need to pass the token boxed as state, or included in some other type you use as state.

这仅在计划使用方法中的CancellationToken时才是必需的.例如,如果您需要调用token.ThrowIfCancellationRequested().

This is only required if you plan to use the CancellationToken within the method, however. For example, if you need to call token.ThrowIfCancellationRequested().

如果您仅使用令牌来阻止方法的调度,则不是必需的.

If you're only using the token to prevent the method from being scheduled, then it's not required.

更多推荐

获取任务CancellationToken

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

发布评论

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

>www.elefans.com

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