简体   繁体   中英

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? WHAT? is this true. I hope not. Can't find anything definite in MSDN.

It totally make cancellation token useless to me i will stick with my thread.abort then.

Yes, it is true. To make use of the CancellationTokenSource your Task must be aware of it.

For example, the following code is aware of the CancellationToken because it calls ThrowIfCancellationRequested() method of the token instance:

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.

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. 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 ). See this question for a bunch of reasons why Thread.Abort is a bad idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM