获取任务CancellationToken [英] Get Task 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!