avo
avo

Reputation: 10701

Disposing of CancellationTokenSource and its child CancellationTokenRegistration

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);
        }
    }
}

Upvotes: 5

Views: 1540

Answers (1)

svick
svick

Reputation: 244757

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.

Upvotes: 9

Related Questions