[英]CancellationTokenSource.Cancel Method Can be ignored by the task cancellation is requested
SO I am reading in book that the task I have passed CancellationTokenSource to even if I call cancel on the token can ignore it? 所以我在书中读到,即使我在令牌上调用cancel,我已将CancellationTokenSource传递给的任务也可以忽略它? WHAT?
什么? is this true.
这是真的。 I hope not.
我希望不是。 Can't find anything definite in MSDN.
在MSDN中找不到任何确定的内容。
It totally make cancellation token useless to me i will stick with my thread.abort then. 这完全使取消令牌对我无用,然后我会坚持使用我的thread.abort。
Yes, it is true. 是的,它是真的。 To make use of the CancellationTokenSource your Task must be aware of it.
要使用CancellationTokenSource,您的任务必须知道它。
For example, the following code is aware of the CancellationToken because it calls ThrowIfCancellationRequested() method of the token instance: 例如,以下代码知道CancellationToken,因为它调用了令牌实例的ThrowIfCancellationRequested()方法:
var cts = new CancellationTokenSource();
SomeCancellableOperation(cts.Token);
...
public void SomeCancellableOperation(CancellationToken token) {
...
token.ThrowIfCancellationRequested();
...
}
I have found the aforementioned code fragment and some clarifications about it in this question . 在这个问题中,我已经找到了上述代码片段以及对其的一些说明。
Yes. 是。 As it says in the documentation ,
CancellationToken
is for cooperative cancellation. 如文档中所述 ,
CancellationToken
用于合作取消。
It is for the code within the task to decide what to do with the information that a cancellation has been requested. 任务中的代码决定如何处理已请求取消的信息。 It can ignore it, or it can wait for an appropriate point and throw an
OperationCanceledException
if cancellation has been requested. 它可以忽略它,也可以等待适当的时间点并在请求取消的情况下抛出
OperationCanceledException
。 There's a helper method provided that does exactly this: 提供了一个可以完全做到这一点的辅助方法:
CancellationToken.ThrowIfCancellationRequested()
This is far preferable to just killing a thread (though, as an aside, Task != Thread
). 这比仅杀死一个线程要好得多(尽管顺便说一句,
Task != Thread
)。 See this question for a bunch of reasons why Thread.Abort
is a bad idea. 看到这个问题的原因有很多,为什么
Thread.Abort
是一个坏主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.