How are CancellationTokens guaranteed to be up-to-date? How are CancellationTokens guaranteed to be up-to-date? multithreading multithreading

How are CancellationTokens guaranteed to be up-to-date?


This is handled internally within CancellationTokenSource. The private variable used to track the CTS's state is marked volatile, which prevents the internal state check from being stale.

My motivation in asking this arises from wondering whether I need my CancellationToken instance variables to be volatile.

You do not need to do this, as the checking is handled internally, and already handled properly for you.

Basically, when you create a CancellationToken from the CancellationTokenSource, the token contains a reference to the original source. This reference can never change, so the call to ThrowIfCancellationRequested checks the state of the source internally. Since the source state is itself volatile, it's never "stale" data.