user1088352
user1088352

Reputation: 411

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.

Upvotes: 1

Views: 961

Answers (2)

Charles Mager
Charles Mager

Reputation: 26213

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.

Upvotes: 1

Stas Ivanov
Stas Ivanov

Reputation: 1245

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.

Upvotes: 1

Related Questions