In C#, where does a CancellationToken.Register callback run, and why must an import service dispose the registrations and linked CancellationTokenSources it creates?
answer
- synchronous, inside someone else's call
- whoever cancels pays
- late registration runs at once
- the long-lived source holds the short-lived ones
basics
~20 sA Register callback runs synchronously on the thread that cancels: inside Cancel(), or on a thread-pool thread when a CancelAfter timer fires. A long-lived source keeps every registration, including a linked source's, until disposed or cancelled.
solid answer
~40 s`CancellationToken.Register` adds a callback to the source's list and returns a `CancellationTokenRegistration`. The callback runs **synchronously** on whichever thread cancels: inside the caller's `Cancel()` call, or on a thread-pool thread when a `CancelAfter` timer fires; if the token is already cancelled, `Register` runs it immediately, inline. `Cancel()` collects callback exceptions into an `AggregateException`, and a timer-fired callback that throws crashes the process, so callbacks must be short and must not throw. The source keeps every registration until it is cancelled or the registration is disposed. A linked source registers on each of its input tokens, and a source with a pending `CancelAfter` is rooted by its timer, so in a service whose session token lives for hours, undisposed per-file sources and registrations accumulate. Dispose what you create, with `using`; never dispose a caller's source.
code
csharp · 19 linesConsole.WriteLine($"Cancel is called on thread {Environment.CurrentManagedThreadId}");
using var cts = new CancellationTokenSource();
cts.Token.Register(() => Console.WriteLine($"close file handle, on thread {Environment.CurrentManagedThreadId}"));
cts.Token.Register(() => throw new InvalidOperationException("progress bar already disposed"));
CancellationTokenRegistration unused = cts.Token.Register(() => Console.WriteLine("never printed"));
unused.Dispose(); // unregistered before cancellation
try
{
cts.Cancel();
}
catch (AggregateException ex)
{
Console.WriteLine($"Cancel() threw AggregateException: {ex.InnerException!.Message}");
}
cts.Token.Register(() => Console.WriteLine("registered late: runs inline, immediately"));
Console.WriteLine("after the late Register call");go deeper
Recall that Register runs a callback when the token is cancelled and returns a registration you can dispose.
Explain that callbacks run synchronously on the cancelling thread, run inline when registered late, and surface exceptions from Cancel().
Diagnose accumulating registrations and linked sources under a long-lived token, the timer-fired crash, and the Dispose-while-running deadlock, and set ownership rules.
Decide how long-lived tokens are exposed to short-lived work across a codebase and how ownership of every source is made obvious in review.
## What Register does `CancellationToken.Register` attaches a callback to the token's source and returns a **`CancellationTokenRegistration`**, a struct whose `Dispose()` removes the callback again. Overloads take an `Action`, an `Action<object?>` plus a state object, or an `Action<object?, CancellationToken>`; one overload adds `bool useSynchronizationContext`. `UnsafeRegister` does the same without capturing the current `ExecutionContext`. Callbacks are how code that is **not** polling the token reacts to cancellation: closing a socket that a blocking read is waiting on, completing a `TaskCompletionSource`, stopping a progress timer. ## Where and when the callback runs | Who triggers cancellation | Where the callbacks run | |---|---| | code calling `cts.Cancel()` | synchronously, on that thread, before `Cancel()` returns | | a `CancelAfter` delay or the `CancellationTokenSource(TimeSpan)` constructor | on a thread-pool thread, when the timer fires | | a linked source's input token | inside whatever cancelled that input | | `cts.CancelAsync()` | asynchronously; the returned `Task` completes after the callbacks have run | | `Register` called on an already-cancelled token | immediately, inline, inside the `Register` call | The consequences: - **The canceller pays.** A Cancel button handler that calls `Cancel()` runs every registered callback on the UI thread before the click handler continues. Slow callbacks freeze the window. - **Exceptions travel to the canceller.** `Cancel()` runs all callbacks, collects their exceptions and then throws an `AggregateException`; `Cancel(throwOnFirstException: true)` lets the first exception escape and skips the callbacks that had not run. When a timer fires the cancellation there is no caller to catch it, and the `AggregateException` is unhandled on a thread-pool thread, which terminates the process. - **Late registration is synchronous too.** Code that registers after cancellation gets its callback run right there, so it must not assume the callback happens later. - The callback runs with the `ExecutionContext` captured at registration (except for `UnsafeRegister`); with `useSynchronizationContext: true`, it is run through `Send` on the `SynchronizationContext` that was current at registration, so the cancelling thread waits for that context. ## Why disposal matters A source keeps a reference to every callback registered on it **until it is cancelled or the registration is disposed**. In the import service, the session's `CancellationTokenSource` lives for hours, while each file's work lasts seconds. Three things then accumulate if nobody disposes them: 1. **Registrations made directly**, such as `sessionToken.Register(() => reader.Close())`. Each keeps its delegate, and everything the delegate captured, reachable from the session source. 2. **Linked sources.** `CreateLinkedTokenSource(sessionToken, ...)` works by registering a callback on each input. An undisposed per-file linked source is therefore reachable from the session source, with its own registrations and state, until the session ends. 3. **Timers.** A source with a pending `CancelAfter` or `TimeSpan` delay holds a timer that keeps it alive until the timer fires. Disposing the source stops the timer. The rule from Microsoft's guidance is simple: **if your code creates a `CancellationTokenSource`, your code disposes it; if a caller passes you a token, never dispose the caller's source.** A `using var` per file covers both the linked source and the per-file timeout source, and a `using var` on a `CancellationTokenRegistration` removes a callback when the file finishes. ## Disposing a registration while it runs `CancellationTokenRegistration.Dispose()` does more than unlink: if the callback is executing at that moment on another thread, `Dispose` **waits for it to finish**, so after it returns you can safely release whatever the callback uses. That wait can deadlock if the disposing thread holds a lock the callback is trying to take. `DisposeAsync()` waits asynchronously instead, and `Unregister()` returns whether it removed the callback, without waiting for one that is already running. ## Practical rules - Keep callbacks short: set a flag, complete a `TaskCompletionSource`, close a handle. - Never throw from a callback; catch inside it if the work can fail. - Do not take locks in a callback that the cancelling code might hold. - Pass state through the `object? state` overload when you want to avoid a closure allocation; what a lambda captures, and for how long, is covered with closures. - Dispose registrations and every source you create, especially when the token you link to is long-lived. The host's shutdown token and a web request's aborted token are covered with ASP.NET Core; the same disposal rules apply to registrations made on them.
- In C#, what is the difference between CancelAsync() and Cancel() on a CancellationTokenSource?`Cancel()` sets the cancelled state and runs every registered callback synchronously before it returns, throwing an `AggregateException` if any callback threw. `CancelAsync()` sets the state synchronously but runs the callbacks asynchronously and returns a `Task` that completes once they have finished. It suits a UI thread that should not run other components' callbacks inline.
- In C#, why can CancellationTokenRegistration.Dispose() deadlock?If the callback is running on another thread when you dispose the registration, `Dispose()` blocks until the callback finishes, so that you can then safely free what the callback uses. If the disposing thread holds a lock that the running callback is waiting for, neither can proceed. `Unregister()` avoids the wait but gives no guarantee that the callback has finished.
- Believes Register callbacks are queued to the thread pool when Cancel() is called
- Lets a Register callback throw, assuming the exception stays inside the token
- Assumes a callback registered on an already-cancelled token never runs
- Skips disposing per-file linked sources because the garbage collector will clean them up
- Disposes the CancellationTokenSource behind a token that a caller passed in
- Does slow I/O inside a callback that the UI thread's Cancel() call will run