Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
        }
    }
}
like image 203
avo Avatar asked Oct 10 '13 02:10

avo


1 Answers

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.

like image 112
svick Avatar answered Sep 22 '22 05:09

svick