Explain, please, on the fingers, why this CancellationToken exists and how to use it. Why the question arose, hooked up a third-party library for working with IMAP, there exists a method that requires the above-described piece as a mandatory parameter, here is the manual .
- docs.microsoft.com/ru-ru/dotnet/standard/threading/… - by Alexcei Shmakov
2 answers
CancellationToken is passed as a parameter and is used to notify the code about the need to cancel the operation . That is, you create a token, transfer it to a third-party code, but if you need to notify this third-party code that you want to cancel the operation, you use this token for this. An example is the first link in MSDN or here's another example.
- Tipo delegate cancellation is obtained? - Winteriscoming
- @Winteriscoming I don't know what you mean by the cancel delegate. If this is a flag that indicates that they want to cancel the operation, then yes) - tym32167
- Well, through this thing, we can interrupt the operation of another method, right? Even in the same thread? - Winteriscoming
- 3@Winteriscoming this thing we can inform another method that we need an interruption - vitidev
- 3@Winteriscoming is not, we can only notify another method that we want to interrupt it. But it will be interrupted or not - it is up to him to decide. - tym32167
As a supplement to the correct answer @ tym32167:
In .NET, cooperative undo is accepted. That is, you must pass inside the operation information that you no longer need its result, and the operation should take care to properly interrupt yourself.
By itself, the cancellation of a token does not cause an interruption of the operation. Usually, the operation scans from time to time at convenient points of accomplishment for this purpose, whether cancellation is required from it, and correctly finishes the work if necessary. (Correct shutdown most often looks outside as an exception throw like OperationCanceledException .)
Breaking off the operation automatically outside, without the cooperation of the operation itself, is quite difficult. The fact is that at the end of the operation, she may have to clean up after herself: delete temporary files, unmack shared memory, exclude herself from the list of current operations, close open windows. External code can not know what exactly the operation needs for correct completion. Therefore, he is not trying to interrupt the operation.
A known exception to this rule is ASP.NET, which sometimes kills threads on its own.