Who Owns a Cancellation? Four UniTask Experiments on Token Lifetime, Timeouts, Dispose and Background Threads

Introduction

Every cancellation bug I ran into came down to one question: who owns this piece of work, and does its token live exactly as long as that owner? My notes said things like “use linked tokens”, “short-lived vs long-lived tokens” and “always Dispose via using“. Rather than trust those notes, I built four small experiments in Unity, logged every step with a timestamp and frame number, and checked each rule against what actually happened.

The four rules under test:

  1. Lifetime. Work should be cancelled by its owner’s lifetime, not by a token borrowed from something that lives longer.
  2. Linked timeout. Combine a global cancel and a local timeout with a linked token, then ask which one fired.
  3. Dispose. The owner of a CancellationTokenSource disposes it, and using is only right when the source lives exactly as long as the method.
  4. Background threads. Passing a token to a thread-pool job is not enough; the worker has to check it.

This is a follow-up to my previous post on swallowing vs. re-throwing OperationCanceledException. That post was about how a cancellation travels. This one is about who owns it.

Setup

  • Unity 6000.0.77f1, UniTask 2.5.11, run in the Editor
  • A fresh project with five scripts: a shared logger (DemoLog.cs) and one script per experiment
  • Each experiment draws its own buttons with IMGUI, so there is no Canvas to wire up
  • Console: Collapse off, cleared before each run
  • Full source

Every log line carries the elapsed time and where it ran: a frame number on the main thread, or a thread ID on a background thread. That stamp is the evidence for everything below.

string where = threadId == _mainThreadId ? $"f{Time.frameCount}" : $"bg-thread {threadId}";
return $"[{t:F2}s | {where}] {msg}";

Unity’s Time API only works on the main thread, so the elapsed time comes from a Stopwatch. That turned out to matter, as the side finding later shows.

Experiment 1: Token lifetime

A panel’s polling loop that borrows the session token keeps running after the panel is destroyed; only ending the whole session stops it. Linking the session token with the panel’s own destroy token stops it one frame after the panel goes away.

The setup has two kinds of work:

  • Long-lived: a session heartbeat every 5 seconds, which should run all session.
  • Short-lived: a panel that polls every second, which should stop when the panel closes.
// BAD: the panel's loop only knows about the session
await UniTask.Delay(pollIntervalMs, cancellationToken: sessionToken);

// GOOD: stop when EITHER the panel is destroyed OR the session ends
CancellationToken panelToken = panel.GetCancellationTokenOnDestroy();
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(sessionToken, panelToken);
await UniTask.Delay(pollIntervalMs, cancellationToken: linkedCts.Token);

Prediction: the BAD loop keeps polling after the panel closes; the GOOD loop stops.

BAD: zombie loops

Exp1 Bad 1
Exp1 Bad 2

[17.31s | f6035] Panel #1: CLOSED (destroyed)
[17.57s | f6139] Panel #1 tick 5: still polling, but my panel is DESTROYED
...
[25.00s | f9187] Panel #2: CLOSED (destroyed)
[25.36s | f9335] Panel #2 tick 4: still polling, but my panel is DESTROYED
[25.58s | f9427] Panel #1 tick 13: still polling, but my panel is DESTROYED

Panel #1 kept polling 0.26 seconds after it was destroyed. After opening and closing a second panel, two zombie loops were polling side by side. Only ending the session stopped them:

[126.42s | f11457] >>> END SESSION <<<
[126.42s | f11457] Session 2: started
[126.42s | f11457] Session 1: heartbeat stopped
[126.42s | f11457] Panel #2: loop stopped (only because the session ended)
[126.42s | f11457] Panel #1: loop stopped (only because the session ended)

GOOD: stops with its owner

Exp1 Good
[175.36s | f20705] Panel #3: CLOSED (destroyed)
[175.37s | f20706] Panel #3: loop stopped (panel closed)
[184.77s | f24423] Panel #4: CLOSED (destroyed)
[184.77s | f24424] Panel #4: loop stopped (panel closed)
[191.84s | f27201] >>> END SESSION <<<
[191.84s | f27201] Panel #5: loop stopped (session ended)

The GOOD loop stopped for either reason, and the log says which one. The heartbeat kept running whenever only a panel closed.

Two details worth noticing

Exactly one frame, every time. Closing a panel and stopping its loop are always one frame apart (f20705 → f20706, f24423 → f24424). Destroy() doesn’t destroy immediately; Unity destroys the object at the end of the frame, the destroy token fires in OnDestroy, and the loop notices on the next frame. By contrast, a direct Cancel() (End session) is noticed in the same frame.

Cancel() returns before anyone reacts. After END SESSION, Session 2: started is logged before Session 1: heartbeat stopped. The code calls Cancel() and then starts the new session immediately; the old loop’s catch only runs afterwards. Cancel() turns a flag on. It doesn’t run the cancelled code for you.

In one sentence: give work a token tied to its real owner. A borrowed, longer-lived token turns closed screens into zombie loops.

Experiment 2: Session + timeout

A download with only a local timeout ignored End session completely: it kept downloading and reported a timeout two seconds after the user had quit. Linking the session token with the timeout stopped it in the same frame, and checking each source told the code which reaction was right.

The simulated download takes 2 seconds on a fast network and 6 seconds on a slow one; the timeout is 4 seconds.

CancellationToken sessionToken = _sessionCts.Token;                  // global, long-lived
using var timeoutCts = new CancellationTokenSource();                // local, short-lived
using var timeoutTimer = timeoutCts.CancelAfterSlim(TimeSpan.FromMilliseconds(TimeoutMs));
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(sessionToken, timeoutCts.Token);

try
{
    await FakeDownloadAsync(linkedCts.Token);
}
catch (OperationCanceledException)
{
    // The linked token only says "something cancelled". Ask each source which one.
    if (sessionToken.IsCancellationRequested)      { /* user quit: leave quietly */ }
    else if (timeoutCts.IsCancellationRequested)   { /* too slow: show 'Retry?' */ }
    else throw;
}

The BAD version uses only timeoutCts. CancelAfterSlim is UniTask’s PlayerLoop-based alternative to CancelAfter, which relies on a thread-pool timer.

Prediction: the GOOD version stops on End session; the BAD version doesn’t.

RunNetworkActionResult
1. GOODfastnoneCOMPLETE at 2.01s
2. GOODslownoneTIMED OUT -> show 'Retry?' dialog at 4.00s
3. GOODslowEnd session at 2.01sABORTED: session ended -> exit quietly in the same frame
4. BADslowEnd session at 2.23skept downloading, then TIMED OUT at 4.00s
[2.01s | f52319] Downloading... 33%
[2.01s | f52320] >>> END SESSION <<<
[2.01s | f52320] ===== GOOD download ABORTED: session ended -> exit quietly, no dialog =====
Exp2 Bad
[2.01s | f66436] Downloading... 33%
[2.23s | f66528] >>> END SESSION <<<
[2.51s | f66639] Downloading... 41%
[3.01s | f66837] Downloading... 50%
[3.51s | f67024] Downloading... 58%
[4.00s | f67229] ===== BAD download TIMED OUT =====

After 2 seconds, run 4 is identical to run 2: the same percentages and the same timeout at 4.00s. In the BAD version, pressing End session had no effect at all. In a real app, a user who had already left would get a “Retry?” dialog.

The order of the checks matters too. If both sources happen to be cancelled, the user has quit, so leaving quietly wins over showing a dialog.

In one sentence: link the global cancel and the local timeout, then ask which one fired, because each needs a different reaction.

Experiment 3: Dispose and using

Forgetting to dispose a linked source leaked about 1 KB each and later cost 82 ms on the main thread when the session ended. Disposing with using kept memory flat. But using combined with a fire-and-forget job made that job impossible to cancel.

Part A: the forgotten linked source

Each button press creates 50,000 linked sources from the session token, registers a callback on each, and either forgets them or disposes them.

// LEAK: the session keeps a registration pointing at every 'linked'
var linked = CancellationTokenSource.CreateLinkedTokenSource(_sessionCts.Token);
linked.Token.Register(OnLinkedCancelled);

// CORRECT: Dispose() unregisters 'linked' from the session
using var linked = CancellationTokenSource.CreateLinkedTokenSource(_sessionCts.Token);
linked.Token.Register(OnLinkedCancelled);

Prediction: memory climbs with LEAK and stays flat with CORRECT.

Exp3 A
StepManaged memory after full GCChange
Baseline673.9 MB
LEAK ×1710.0 MB+36.1 MB
LEAK ×2763.5 MB+53.5 MB
LEAK ×3831.2 MB+67.7 MB
End session671.0 MBback to baseline
CORRECT ×3666.2 MB each timeflat
End session666.2 MBflat

Two results stood out:

  • About 1 KB per forgotten source. 150,000 leaked sources added about 157 MB. They were kept alive only by the session’s registrations, so the memory came back the moment the session ended. A linked source you don’t dispose lives exactly as long as its parent.
  • The leak also costs time. Ending the session after the leak logged Session Cancel() took 82 ms and ran 150,000 callbacks belonging to linked sources whose work had already finished. That’s about 5 frames at 60 fps, spent on work that was already done, at the exact moment of a reset or scene change. After the CORRECT runs: 0 ms and ran 0 callbacks.

Part B: who owns the source?

// PITFALL: 'using' disposes the CTS when this method returns, but the job keeps running
void StartJobPitfall()
{
    using var cts = CancellationTokenSource.CreateLinkedTokenSource(_sessionCts.Token);
    LongJobAsync("PITFALL", cts.Token).Forget();
}

// CORRECT: a field owns the CTS and disposes it when replacing it or on destroy
_ownedCts?.Cancel();
_ownedCts?.Dispose();
_ownedCts = CancellationTokenSource.CreateLinkedTokenSource(_sessionCts.Token);
LongJobAsync("OWNED", _ownedCts.Token).Forget();
Exp3 B
[0.00s | f62440] PITFALL job START
[0.00s | f62440] PITFALL: method returned -> 'using' disposed the CTS while the job still runs
[4.00s | f63947] PITFALL job: 4/10
[4.19s | f64018] >>> CANCEL PITFALL JOB <<<
[4.19s | f64018] PITFALL: Cancel() threw ObjectDisposedException -> this job can't be stopped
[5.00s | f64327] PITFALL job: 5/10
...
[10.01s | f66092] PITFALL job COMPLETED

[3.86s | f88674] >>> CANCEL OWNED JOB <<<
[3.86s | f88674] OWNED job ABORTED

The job started and its source was disposed in the same frame (f62440). From then on, nothing could stop it: Cancel() threw ObjectDisposedException, and the job ran to completion. The owned version stopped in the same frame as the Cancel press.

This corrected one of my own notes. “Always dispose every CancellationTokenSource with using” is only half right. The rule is: whoever owns the source disposes it at the end of its life, and using is correct only when that life is the method’s scope.

In one sentence: dispose linked sources, but dispose them when their owner is done, not when the method that created them returns.

Experiment 4: Tokens into background threads

Passing a token only to UniTask.RunOnThreadPool didn’t stop the work: five more chunks ran after Cancel, and the job then reported ABORTED anyway. When the worker checked the token between chunks, it stopped 0.05 seconds after Cancel. The unchecked worker even kept running after I left Play Mode.

The job is 10 chunks of 0.5 seconds each on a thread-pool thread. Thread.Sleep stands in for CPU-heavy work such as parsing or pathfinding.

// BAD: the token only goes to RunOnThreadPool; the worker never looks at it
await UniTask.RunOnThreadPool(() => HeavyWorkBad(), cancellationToken: ct);

// GOOD: the worker checks the token before every chunk
static void HeavyWorkGood(CancellationToken ct)
{
    for (int chunk = 1; chunk <= Chunks; chunk++)
    {
        ct.ThrowIfCancellationRequested();
        Thread.Sleep(ChunkMs);
        DemoLog.Info($"Processed chunk {chunk}/{Chunks}");
    }
}

Prediction: the BAD job finishes all 10 chunks after Cancel; the GOOD job stops within one chunk.

BAD

Exp4 Bad
[2.51s | bg-thread 2236] Processed chunk 5/10
[2.69s | f14136] >>> CANCEL BUTTON PRESSED <<<
[3.01s | bg-thread 2236] Processed chunk 6/10
...
[5.01s | bg-thread 2236] Processed chunk 10/10
[5.01s | f15153] ===== BAD job ABORTED =====

All the work after Cancel still ran, and the job was then reported as aborted. That is the worst of both: the cost of finishing, with the result of cancelling. As far as I can tell from UniTask’s source, RunOnThreadPool checks the token before starting and again after the work returns, but it can’t interrupt the work itself.

GOOD

Exp4 Good
[1.50s | bg-thread 2229] Processed chunk 3/10
[1.96s | f26295] >>> CANCEL BUTTON PRESSED <<<
[2.00s | bg-thread 2229] Processed chunk 4/10
[2.01s | f26314] ===== GOOD job ABORTED =====

The chunk already in progress finished, then the check before chunk 5 stopped it. Cancellation in a worker is only as fast as the chunk size: smaller chunks stop sooner, at the cost of checking more often.

The log also shows the thread switch: every “Processed” line says bg-thread, and the START and ABORTED lines carry a frame number again, because UniTask returns to the main thread after the work.

Leaving Play Mode

I started the BAD job and then exited Play Mode.

Exp4 Leaving PlayMode
[4.56s | bg-thread 2292] Processed chunk 9/10
[5.07s | bg-thread 2292] Processed chunk 10/10
[5.07s | f3] ===== BAD job ABORTED =====

The worker kept going to 10/10 after the game had stopped. The final line has frame number 3, which is the frame counter after leaving Play Mode. My best explanation is that UniTask still processes continuations in Edit Mode, and the token linked to the component’s destruction reported the cancel. Either way, stopping Play Mode does not stop background threads: a worker writing files or calling a server would keep going in the Editor.

In one sentence: a background worker must check the token itself; handing it to the thread pool is not enough.

Side finding: UniTask.Delay is not a wall clock

During Experiment 1, the log suddenly jumped from 29.58s to 125.91s, about 96 seconds, yet only 276 frames passed and each loop ticked just once. At my frame rate of about 400 fps, 276 frames is less than one second of running.

The cause was me: I had paused the Editor while reading notes. With no frames, game time stopped, and UniTask.Delay counts game time by default. The timestamp column comes from a Stopwatch, which counts real time and kept going. A second, deliberate pause showed the same pattern: 17 seconds of real time, 374 frames, and after unpausing, the next tick arrived one game second later. There was no burst of “missed” ticks.

I then tested Run In Background (Edit → Project Settings → Player → Resolution and Presentation). I opened a polling panel, switched to another window for about 10 seconds, and came back.

Run In BackgroundWhile I was in another windowFrames during that time
OnTicks every second, heartbeats every 5 seconds, no breakabout 4,100 frames in 10 s
OffNothing for about 10.5 s197 frames in 10.5 s

With the setting off, the Editor’s Play Mode stopped when it lost focus, and every UniTask.Delay stopped with it. With it on, everything kept running.

This matters beyond the Editor. Anything that stops game time, such as pausing, Time.timeScale = 0, or an app losing focus, also stops game-time delays and timeouts like CancelAfterSlim. If a timeout must follow real time, it has to be asked for explicitly, for example with DelayType.Realtime.

Takeaways

All four rules held, and each one now has a number behind it.

RuleWhat happened without itEvidence
Tie work to its owner’s lifetimeClosed panels kept polling as zombie loops until the session endedExp 1
Link global cancel + local timeout, then ask which one firedEnd session had no effect; a user who quit would still see “Retry?”Exp 2
The owner disposes; using only for method-scoped sources~1 KB leaked per linked source, 82 ms of stale callbacks on reset; using + Forget() made a job uncancellableExp 3
Background workers check the token themselves5 chunks ran after Cancel; the worker outlived Play ModeExp 4

The common thread is ownership. A token is only useful if it is cancelled when its owner goes away, and if the code doing the work actually looks at it. Most of the bugs here came from a mismatch between those two: a token that lived too long, a source that was disposed too early, or a worker that never checked.

Running these experiments also changed how I read my own notes. Two of them (“always use using” and “pass the token into the background”) were half true, and only the logs showed which half.

What I didn’t test, and open questions

  • Editor only. Every run was in the Unity Editor. Frame timings and memory numbers will differ in a player build and on device.
  • One or two runs per case. The direction of each result (zombies vs. none, memory up vs. flat) was clear, but I didn’t measure the numbers repeatedly.
  • Why the leak grew faster each time. Each LEAK batch added more memory than the last (+36, +54, +68 MB). My guess is the session’s internal callback list resizing as it grows; I haven’t verified it.
  • The late first heartbeat. In every session, the first 5-second heartbeat arrived about 1 to 1.5 seconds late. My guess is a slow first frame when Play Mode starts, counted as only part of a second because Unity caps a single frame’s deltaTime. Unverified.
  • The Edit Mode ABORTED line. The explanation that UniTask still processes continuations in Edit Mode fits the log, but I didn’t confirm it in the source.
  • Not covered: TimeoutController, DelayType.Realtime timeouts, and destroyCancellationToken (Unity’s built-in alternative to GetCancellationTokenOnDestroy).

Leave a Comment