When to dispose CancellationTokenSource?

Viewed 67643

The class CancellationTokenSource is disposable. A quick look in Reflector proves usage of KernelEvent, a (very likely) unmanaged resource. Since CancellationTokenSource has no finalizer, if we do not dispose it, the GC won't do it.

On the other hand, if you look at the samples listed on the MSDN article Cancellation in Managed Threads, only one code snippet disposes of the token.

What is the proper way to dispose of it in code?

  1. You cannot wrap code starting your parallel task with using if you do not wait for it. And it makes sense to have cancellation only if you do not wait.
  2. Of course you can add ContinueWith on task with a Dispose call, but is that the way to go?
  3. What about cancelable PLINQ queries, which do not synchronize back, but just do something at the end? Let's say .ForAll(x => Console.Write(x))?
  4. Is it reusable? Can the same token be used for several calls and then dispose it together with the host component, let's say UI control?

Because it does not have something like a Reset method to clean-up IsCancelRequested and Token field I would suppose it's not reusable, thus every time you start a task (or a PLINQ query) you should create a new one. Is it true? If yes, my question is what is the correct and recommended strategy to deal with Dispose on those many CancellationTokenSource instances?

7 Answers

It has been a long time since I asked this and got many helpful answers but I came across an interesting issue related to this and thought I would post it here as another answer of sorts:

You should call CancellationTokenSource.Dispose() only when you are sure that nobody is going to try to get the CTS's Token property. Otherwise you should not call Dispose(), because it creates a race condition. For instance, see here:

https://github.com/aspnet/AspNetKatana/issues/108

In the fix for this issue, code which previously did cts.Cancel(); cts.Dispose(); was edited to just do cts.Cancel(); because anyone so unlucky as to try to get the cancellation token in order to observe its cancellation state after Dispose has been called will unfortunately also need to handle ObjectDisposedException - in addition to the OperationCanceledException that they were planning for.

Another key observation related to this fix is made by Tratcher: "Disposal is only required for tokens that won't be cancelled, as cancellation does all of the same cleanup." i.e. just doing Cancel() instead of disposing is really good enough!

I wrote a thread-safe class that binds a CancellationTokenSource to a Task, and guarantees that the CancellationTokenSource will be disposed when its associated Task completes. It uses locks to ensure that the CancellationTokenSource will not be canceled during or after it has been disposed. This happens for compliance with the documentation, that states:

The Dispose method must only be used when all other operations on the CancellationTokenSource object have completed.

And also:

The Dispose method leaves the CancellationTokenSource in an unusable state.

Here is the CancelableExecution class:

public class CancelableExecution
{
    private readonly bool _allowConcurrency;
    private Operation _activeOperation;

    // Represents a cancelable operation that signals its completion when disposed
    private class Operation : IDisposable
    {
        private readonly CancellationTokenSource _cts;
        private readonly TaskCompletionSource _completionSource;
        private bool _disposed;

        public Task Completion => _completionSource.Task; // Never fails

        public Operation(CancellationTokenSource cts)
        {
            _cts = cts;
            _completionSource = new TaskCompletionSource(
                TaskCreationOptions.RunContinuationsAsynchronously);
        }

        public void Cancel() { lock (this) if (!_disposed) _cts.Cancel(); }

        void IDisposable.Dispose() // It is disposed once and only once
        {
            try { lock (this) { _cts.Dispose(); _disposed = true; } }
            finally { _completionSource.SetResult(); }
        }
    }

    public CancelableExecution(bool allowConcurrency)
    {
        _allowConcurrency = allowConcurrency;
    }
    public CancelableExecution() : this(false) { }

    public bool IsRunning => Volatile.Read(ref _activeOperation) != null;

    public async Task<TResult> RunAsync<TResult>(
        Func<CancellationToken, Task<TResult>> action,
        CancellationToken extraToken = default)
    {
        ArgumentNullException.ThrowIfNull(action);
        CancellationTokenSource cts = CancellationTokenSource
            .CreateLinkedTokenSource(extraToken);
        using Operation operation = new(cts);
        // Set this as the active operation
        Operation oldOperation = Interlocked
            .Exchange(ref _activeOperation, operation);
        try
        {
            if (oldOperation is not null && !_allowConcurrency)
            {
                oldOperation.Cancel();
                // The Operation.Completion never fails.
                await oldOperation.Completion; // Continue on captured context.
            }
            cts.Token.ThrowIfCancellationRequested();
            // Invoke the action on the initial SynchronizationContext.
            Task<TResult> task = action(cts.Token);
            return await task.ConfigureAwait(false);
        }
        finally
        {
            // If this is still the active operation, set it back to null.
            Interlocked.CompareExchange(ref _activeOperation, null, operation);
        }
        // The operation is disposed here, along with the cts.
    }

    public Task RunAsync(Func<CancellationToken, Task> action,
        CancellationToken extraToken = default)
    {
        ArgumentNullException.ThrowIfNull(action);
        return RunAsync<object>(async ct =>
        {
            await action(ct).ConfigureAwait(false);
            return null;
        }, extraToken);
    }

    public Task CancelAsync()
    {
        Operation operation = Volatile.Read(ref _activeOperation);
        if (operation is null) return Task.CompletedTask;
        operation.Cancel();
        return operation.Completion;
    }

    public bool Cancel() => CancelAsync().IsCompleted == false;
}

The primary methods of the CancelableExecution class are the RunAsync and the Cancel. By default concurrent (overlapping) operations are not allowed, meaning that calling RunAsync a second time will silently cancel and await the completion of the previous operation (if it's still running), before starting the new operation.

This class can be used in applications of any kind. Its primary intended usage though is in UI applications, inside forms with buttons for starting and canceling an asynchronous operation, or with a listbox that cancels and restarts an operation every time its selected item is changed. Here is an example of the first use-case:

private readonly CancelableExecution _cancelableExecution = new();

private async void btnExecute_Click(object sender, EventArgs e)
{
    string result;
    try
    {
        Cursor = Cursors.WaitCursor;
        btnExecute.Enabled = false;
        btnCancel.Enabled = true;
        result = await _cancelableExecution.RunAsync(async ct =>
        {
            await Task.Delay(3000, ct); // Simulate some cancelable I/O operation
            return "Hello!";
        });
    }
    catch (OperationCanceledException)
    {
        return;
    }
    finally
    {
        btnExecute.Enabled = true;
        btnCancel.Enabled = false;
        Cursor = Cursors.Default;
    }
    this.Text += result;
}

private void btnCancel_Click(object sender, EventArgs e)
{
    _cancelableExecution.Cancel();
}

The RunAsync method accepts an extra CancellationToken as argument, that is linked to the internally created CancellationTokenSource. Supplying this optional token may be useful in advanced scenarios.

For a version compatible with the .NET Framework, you can look at the 3rd revision of this answer.

Related