문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top