Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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).

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.

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