Why is the following even legal?
CancellationToken.None.Register(delegate { });
Why does, for example, Register
not throw an exception here? Is it because the above amounts to a NOP?
Background: The reason for asking this question is to understand whether a method accepting a CancellationToken
needs to be coded defensively against CancellationToken.None
when registration is involved.
Whether you're doing async work or not, accepting a CancellationToken as a parameter to your method is a great pattern for allowing your caller to express lost interest in the result. Supporting cancelable operations comes with a little bit of extra responsibility on your part.
Gets a Task that will complete when this Task completes or when the specified CancellationToken has cancellation requested.
CancellationTokens for Advanced EventsThey are thread-safe out of the box.
However, the cancellation token itself is not usually relevant to the core functionality of a majority of these methods. It's considered a good API design practice to have such parameters be the last parameter in the list.
CancellationToken.None is not a null reference, but rather an empty cancellation token. As such, it does have an instance. The registration will never fire, as the source will never register as being cancelled, but it will go through "properly."
I would still put a check and code defensively against this, however, unless you are careful about Disposing the CancellationTokenRegistration returned properly.
Edit:
Upon further investigation, if you register against CancellationToken.None
, you will effectively be doing nothing, and the CancellationTokenRegistration
returned will not require disposal. This will not keep a reference to your object or delegate, and not form a leak, so it is a no-op for practical purposes. This should be safe to do, and should not require defensive practices to avoid on your end.
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