Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top