Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create a Hierarchical CancellationTokenSource?

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.

like image 511
momt99 Avatar asked Oct 10 '21 15:10

momt99


People also ask

How do I create a CancellationToken?

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.

Can a CancellationTokenSource be reused?

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.

Should I dispose CancellationTokenSource?

You should always dispose CancellationTokenSource .

Is CancellationTokenSource thread safe?

Cancellation tokens are generally thread safe by design so passing them between threads and checking them should not be a problem.


1 Answers

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
like image 170
Theodor Zoulias Avatar answered Nov 14 '22 22:11

Theodor Zoulias