Does Dispose()
of CancellationTokenSource
also dispose of any child CancellationTokenRegistration
objects obtained via Token.Register()
? Or must I individually dispose of each registration?
Example 1:
async Task GoAsync(CancellationToken ct1, CancellationToken ct2)
{
using (var cts = CancellationTokenSource.CreateLinkedTokenSource(ct1, ct2))
{
cts.Token.Register(() => Debug.Print("cancelled"), false)
await Task.Delay(1000, cts.Token);
}
}
Example 2:
async Task GoAsync(CancellationToken ct1, CancellationToken ct2)
{
using (var cts = CancellationTokenSource.CreateLinkedTokenSource(ct1, ct2))
{
using (cts.Token.Register(() => Debug.Print("cancelled"), false))
{
await Task.Delay(1000, cts.Token);
}
}
}
Contrary to what the documentation says, you don't dispose CancellationTokenRegistration
to release resources, you do it to make the registration invalid. That is, you don't want the registered delegate to fire anymore, even if the token is canceled.
When you dispose the CancellationTokenSource
, it means the associated token can't be canceled anymore. This means that you can be sure that the registered delegate won't fire, so there is no reason to dispose the registration in this case.
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