Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to register with CancellationToken.None?

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.

like image 581
Atif Aziz Avatar asked Mar 30 '11 17:03

Atif Aziz


People also ask

Should I use CancellationToken?

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.

What does CancellationToken none do?

Gets a Task that will complete when this Task completes or when the specified CancellationToken has cancellation requested.

Is CancellationToken thread safe?

CancellationTokens for Advanced EventsThey are thread-safe out of the box.

Should CancellationToken be the last parameter?

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.


1 Answers

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.

like image 175
Reed Copsey Avatar answered Oct 01 '22 00:10

Reed Copsey