Being able to reuse same CancellationTokenSource - CancellationTokenSource.CreateLinkedTokenSource

Viewed 420

I'm trying to figure out what CancellationTokenSource.CreateLinkedTokenSource actually does. I know it's a regular cancellation source that is also "linked" to an existing token.

The following snippet does the following:

  • prints a message > cancels the task -> starts the task again -> prints a message -> cancels the task again and so on.

It's actually reusing same cts instance over and over again. Is that behavior coming from CancellationTokenSource.CreateLinkedTokenSource? I mean when a CancellationTokenSource is canceled, I shouldn't be able to use it again, unless I create a new one instead.

If that's the case, why does the snippet pass a CancellationToken to the Start method, when we never actually cancel the cts, but the linked one?

// Program.cs
var cts = new CancellationTokenSource();

await foreach (var item in items.Start(cts.Token))
{
    Console.WriteLine(item);
    item.Stop();
    item.Start(cts.Token);
}
private CancellationTokenSource? _cts;

public IAsyncEnumerable<string> Start(CancellationToken cancellationToken)
{
    _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

    ...
}

public void Stop()
{
    _cts?.Cancel();
}
1 Answers

Once Cancel() is issued and you want to reuse the CancellationTokenSource perform a check via IsCancellationRequested, if true than Dispose _cts and recreate _cts.

if (_cts.IsCancellationRequested)
{
    _cts.Dispose();
    _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
}
Related