In our project, we have decided to provide a cancellation mechanism for users with the help of CancellationToken
.
Because of the structure of the works in the project, I need a hierarchical cancellation mechanism. By hierarchical, I mean that parent source cancellation causes all child sources to be recursively canceled but child sources cancellations are not propagated to the parent.
Is there such an option available in .NET out of the box? If not, I'm not sure whether registering a delegate to the parent token is enough or further considerations should be given.
You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource. Token property. You then pass the cancellation token to any number of threads, tasks, or operations that should receive notice of cancellation.
CancellationTokenSource is quite a heavyweight object and its not normally cancelled; however it can't be pooled or reused because its registrations cannot be cleared.
You should always dispose CancellationTokenSource .
Cancellation tokens are generally thread safe by design so passing them between threads and checking them should not be a problem.
Yes, this functionality exists out of the box. Check out the CancellationTokenSource.CreateLinkedTokenSource
method.
Creates a
CancellationTokenSource
that will be in the canceled state when any of the source tokens are in the canceled state.
Example:
using var parentCts = new CancellationTokenSource();
using var childrenCts = CancellationTokenSource
.CreateLinkedTokenSource(parentCts.Token);
parentCts.Cancel(); // Cancel the children too
childrenCts.Cancel(); // Doesn't affect the parent
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With