CancellationToken.Register
returns a CancellationTokenRegistration
instance. If you call Dispose
on that instance, your registration will be removed.
CancellationToken UnRegister Action
-
07-12-2021 - |
Pergunta
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?
Solução
Outras dicas
You can safely dispose the entire CancellationTokenSource. Without worry about unregister callbacks.
The Dispose() method of the CancellationTokenSource will call dispose on every registered callback you added into your Token via Token.Register(callBack).
There is no way to really undo a registration. While the dispose method will remove the callback the token still contains the information that there is a registration:
var cancellationTokenSource = new CancellationTokenSource();
basicTask = Task.Factory.StartNew(() => {
for (;;) {
var z = DateTime.Today.ToString();
}
}, cancellationTokenSource.Token);
var basicTask2 = Task.Factory.StartNew(() => {
for (;;) {
var z = DateTime.Today.ToString();
}
}, cancellationTokenSource.Token);
//var usingThisCodeWillResultInADeadlock = cancellationTokenSource.Token.Register(() => { });
//usingThisCodeWillResultInADeadlock.Dispose();
cancellationTokenSource.Cancel();
basicTask.Wait();
Disabling the comments will result in a deadlock.