Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CancellationToken UnRegister Action

I have a token for various tasks and I need to better manage their cancellation, to be notified of a cancellation I can use:

token.Register(RegisterMethod); 

How can I remove this "subscription"? Is there any way to "UnRegister"?

I thought about doing a workaround with TaskCompletionSource. But I do not know if it would work well. What is the best way to solve this approach?

like image 421
J. Lennon Avatar asked Dec 13 '12 16:12

J. Lennon


People also ask

How do I cancel a CancellationToken?

A CancellationToken can only be created by creating a new instance of CancellationTokenSource . CancellationToken is immutable and must be canceled by calling CancellationTokenSource. cancel() on the CancellationTokenSource that creates it. It can only be canceled once.

Does disposing a CancellationTokenSource cancel it?

The Dispose method leaves the CancellationTokenSource in an unusable state. After calling Dispose , you must release all references to the CancellationTokenSource so the garbage collector can reclaim the memory that the CancellationTokenSource was occupying.

Can I reuse CancellationTokenSource?

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.


2 Answers

CancellationToken.Register returns a CancellationTokenRegistration instance. If you call Dispose on that instance, your registration will be removed.

like image 102
Richard Deeming Avatar answered Oct 02 '22 19:10

Richard Deeming


You can safely dispose the entire CancellationTokenSource. Without worry about unregister callbacks.

Code: https://github.com/microsoft/referencesource/blob/master/mscorlib/system/threading/CancellationTokenSource.cs#L552

The Dispose() method of the CancellationTokenSource will call dispose on every registered callback you added into your Token via Token.Register(callBack).

like image 29
Fernando Zago Avatar answered Oct 02 '22 19:10

Fernando Zago