GuidesCancel work on dispose
Cancel work on dispose
Cancel a token when a scope ends, with a source the disposable creates or one you own.
Work that waits on a CancellationToken should stop when the scope that started it ends. A cancellation disposable cancels its token when you dispose it, so a using block is enough to stop the work. This page shows how to cancel when the scope ends, how to cancel a source you own, how to cancel asynchronously, and what to watch for.
Cancel when the scope ends
Section titled “Cancel when the scope ends”Disposable.Cancellation() creates its own CancellationTokenSource and exposes its Token. The first Dispose cancels the token, then disposes the source it created.
using var cancellation = Disposable.Cancellation();var work = Task.Delay(Timeout.Infinite, cancellation.Token);cancellation.Dispose(); // cancels the token, then disposes the source it created// work.IsCanceled == trueCancel a source you own
Section titled “Cancel a source you own”Disposable.Cancellation(source) cancels a source that you created, and leaves it to you to dispose. The token keeps working after Dispose, because the source is still alive.
using var source = new CancellationTokenSource();var cancellation = Disposable.Cancellation(source);
cancellation.Dispose(); // cancels the source and leaves it to you to dispose
// true: Token still works, so the source is not disposedvar cancelled = source.Token.IsCancellationRequested;Cancel asynchronously
Section titled “Cancel asynchronously”AsyncDisposable.Cancellation() does the same through DisposeAsync: it cancels with CancelAsync, then disposes the source it created.
var cancellation = AsyncDisposable.Cancellation();var work = Task.Delay(Timeout.Infinite, cancellation.Token);
await cancellation.DisposeAsync(); // CancelAsync, then disposes the source it created
// work.IsCanceled == truePitfalls
Section titled “Pitfalls”A token callback that throws makes Dispose throw an AggregateException:
var cancellation = Disposable.Cancellation();cancellation.Token.Register(() => throw new InvalidOperationException("Callback failed."));
var failed = false;try{ cancellation.Dispose();}catch (AggregateException){ failed = true; // the callback's exception, after the source was disposed}- Expecting your source to be disposed.
- You write
Disposable.Cancellation(source). - What happens: it cancels the source and never disposes it.
- Write instead: dispose the source yourself, through
using, or letDisposable.Cancellation()create it.
- You write
- A token callback that throws.
- You write
token.Register(() => throw …). - What happens:
DisposethrowsAggregateExceptionafter it disposed a source it created. - Write instead: catch exceptions inside the callback.
- You write