42

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?

2

3 Answers 3

93

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

1
  • 2
    had missed this, thank you. Although it would be nice if this could be done directly on token ..
    – J. Lennon
    Commented Dec 13, 2012 at 19:07
3

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

-6

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.

2
  • 5
    I am not sure what you wanted to show -- your basicTask2 is unused, your basicTask has infinite loop inside, so no matter what you cannot stop it or cancel it, and you wait for that task which (by definition) never ends. Uncommenting those 2 lines does not change a thing. Commented Oct 7, 2016 at 10:36
  • 1
    You must be joking. Have you misread the question, or have you never looked what CancellationToken.Register returns? Commented Apr 23, 2020 at 13:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.