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?
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.
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.
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.
CancellationToken.Register
returns a CancellationTokenRegistration
instance. If you call Dispose
on that instance, your registration will be removed.
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).
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