Asynchronous cancellation
Follow cancellation from .NET tokens through Promise and web APIs, separating a stop request, actual termination, and stale results.
· Last updated: 2026-11-07 · 10 min read
Overview
Cancellation lets a caller tell an in-flight operation that its work is no longer wanted. Without it, a closed modal keeps pulling down a 50 MB image in the background, or a slow response to an earlier search query lands last and clobbers the results of the query the user just typed.
Three distinct layers hide inside the word “cancel”: abandoning the caller's wait, halting the underlying computation or socket transfer, and refusing to apply a result that already finished. Which layer actually stops depends entirely on the API contract.
Once an asynchronous job is airborne, the caller rarely holds direct control over its execution. Packets are already on the wire, file reads sit inside OS kernel queues, or a tight loop is occupying a worker thread; consequently, most modern APIs rely on cooperative cancellation, where the caller flips a cancellation signal and the running operation checks or subscribes to that signal to clean up and exit safely.
Here lifetime management meets concurrency control. Because a newer search and an older search can finish out of order, trying to save work by stopping the old request and guarding who still has permission to mutate screen state are two halves of one design.
Chronology
May 2009: In “.NET 4 Cancellation Framework” on the Microsoft .NET Blog, Mike Liddell introduced the .NET 4 design, separating
CancellationTokenSourcefor requesting cancellation fromCancellationTokenpassed to the operation across .NET 4's parallel and asynchronous APIs.1April 2010:
CancellationTokenSourceandCancellationTokenbecame part of .NET Framework 4.23March 2015: Issue #27, “Aborting a fetch,” opened in the WHATWG fetch repository to discuss a cancellation interface.45
June 2015: ECMAScript 2015, the sixth edition of ECMA-262, included Promise in the JavaScript standard.6
2017: Browsers began shipping fetch cancellation. Jake Archibald’s “Abortable fetch” traces the discussion from 2015; its correction identifies Edge 16 as the first browser to ship support.4
Forced interruption and cooperative cancellation
Introducing the .NET 4 cancellation framework in May 2009, Mike Liddell contrasted forced thread termination with cooperative cancellation. Killing a thread mid-flight can leave shared data half-mutated and locks or file handles leaked, whereas cooperative cancellation asks the operation to notice a signal at a safe point and run its own cleanup before exiting.1
Before .NET 4, cancellation APIs also fragmented across types. When every worker class invents its own Cancel() method or boolean flag, wiring one timeout to cancel four different operations, or cancelling just one run of a reusable service object, gets clumsy fast, which is why the worker object and the lifetime of a single execution need separate types.
.NET split those roles into CancellationTokenSource and CancellationToken: the caller holds the source to trigger cancellation, while the operation receives only the read-only token to poll or register a callback on.1 Authority to cancel and responsibility for reacting stay visibly separate in type signatures, and current .NET guidance still frames cooperative cancellation around requesting, observing, and cleaning up, noting that a gap always exists between the instant cancellation is requested and the moment the work actually stops.7
Waiting for a result and stopping execution
In JavaScript, an ES2015 Promise represents an eventual value that transitions from pending to fulfilled or rejected, not a handle to control the worker producing it.6 Because multiple callers can await the same Promise, and the Promise itself does not care whether its producer is a network socket, a timer, or a CPU task, waiting for a result and controlling execution lifetime require separate objects.
Racing a request against a timer with Promise.race lets the caller stop waiting on time. Yet the losing request keeps burning sockets or CPU in the background unless a cancellation signal is wired into the producer itself.
Cancellation signals and authority to apply results
On the web platform, DOM's AbortController and AbortSignal play the exact same requester/observer duet as .NET: calling controller.abort() stamps the signal as aborted with a reason, and any API holding that AbortSignal decides how to tear down its own work.8
The DOM specification defines AbortSignal as a general-purpose abort primitive, and the Fetch specification hooks it into both the initial HTTP request and the streaming response body. Receiving the Response headers does not mean the transfer is over; aborting while the body stream is still being read tears down the remaining download mid-stream.89
Cooperative cancellation always moves through four beats: request, observation, cleanup, and completion. Handing an AbortSignal to a synchronous CPU loop that never checks signal.aborted and never yields to the event loop accomplishes nothing until the loop finishes on its own.
Remote writes have their own independent lifetime. Aborting a browser fetch after the packet left the machine will not roll back a transaction the server already committed, so undoing remote side effects requires an explicit server-side cancellation endpoint or status check.
Even pure reads race each other. Start search A, then immediately start search B, and if A returns last it will overwrite B's screen state unless you guard the update. React's official Effect cleanup documentation addresses this exact race by ignoring stale responses.10
Stopping wasted work and guarding state authority belong together. Tagging each request with a generation counter or dedicated abort controller lets you gate success updates, error banners, and loading spinners under one rule, as well as decide which child tasks must die when a parent view unmounts.
Reading cancellation state
The short script below inspects an AbortSignal before and after its AbortController fires.
function inspect(signal: AbortSignal): string {
return signal.aborted ? 'cancelled' : 'ready';
}
const controller = new AbortController();
console.log(inspect(controller.signal));
controller.abort();
console.log(inspect(controller.signal));
It prints ready and then cancelled: abort() flips the signal's state and inspect reads it, ready to be wired into an observation loop or an abort-aware API like fetch.
Guarding result ownership when completion order reverses
How do signaling cancellation and checking permission to update state fit together in code? The model below assigns each search a monotonically increasing revision, installs a fresh AbortController, and aborts the previous controller whenever a new search starts.
type ViewState =
| { kind: 'idle' | 'loading' | 'cancelled' }
| { kind: 'ready'; value: string }
| { kind: 'failed'; message: string };
type Load = (query: string, signal: AbortSignal) => Promise<string>;
type Outcome = 'applied' | 'superseded' | 'cancelled' | 'failed';
function createSearch(load: Load) {
let revision = 0;
let active: AbortController | null = null;
let state: ViewState = { kind: 'idle' };
async function run(query: string): Promise<Outcome> {
const mine = ++revision;
const previous = active;
const controller = new AbortController();
active = controller;
state = { kind: 'loading' };
previous?.abort();
try {
if (mine !== revision) return 'superseded';
if (controller.signal.aborted) return 'cancelled';
const value = await load(query, controller.signal);
if (mine !== revision) return 'superseded';
if (controller.signal.aborted) {
state = { kind: 'cancelled' };
return 'cancelled';
}
state = { kind: 'ready', value };
return 'applied';
} catch (cause) {
if (mine !== revision) return 'superseded';
if (controller.signal.aborted) {
state = { kind: 'cancelled' };
return 'cancelled';
}
state = { kind: 'failed', message: String(cause) };
return 'failed';
} finally {
if (mine === revision) active = null;
}
}
return {
run,
read: () => state,
cancel() {
const controller = active;
if (controller) {
active = null;
state = { kind: 'cancelled' };
controller.abort();
}
},
};
}
async function main() {
let finishOld!: (value: string) => void;
const oldResult = new Promise<string>(resolve => { finishOld = resolve; });
const search = createSearch((query, _signal) =>
query === 'old' ? oldResult : Promise.resolve('NEW'));
const oldRun = search.run('old');
console.log(await search.run('new'));
finishOld('OLD');
console.log(await oldRun);
console.log(JSON.stringify(search.read()));
}
void main();applied
superseded
{"kind":"ready","value":"NEW"}Here load deliberately ignores _signal so that the older request still resolves after new has already finished. Even though old completes last, the mine !== revision check marks it 'superseded' and preserves {"kind":"ready","value":"NEW"}. Wiring a real fetch(url, { signal }) into load lets signal tear down in-flight network work early while the revision check still blocks any late response that crossed the finish line just before abort() fired.
Why failures and cleanup need the same ownership check
Guarding only the success path leaves two other races open: an obsolete request's catch block can overwrite the current screen with a stale error, or its finally block can clear the active controller belonging to the newer request. Checking mine === revision across try, catch, and finally, and assigning active = controller before calling previous?.abort() in case an abort listener synchronously triggers another run, closes both gaps.
See also
Footnotes
- Mike Liddell, “.NET 4 Cancellation Framework,” Microsoft .NET Blog, May 22, 2009. Article. ↩
- Microsoft, “Cancellation” (.NET Framework 4 archived documentation). Describes the unified cooperative cancellation model introduced in .NET Framework 4 around CancellationTokenSource and CancellationToken. Official documentation. ↩
- Microsoft, “Microsoft .NET Framework - Microsoft Lifecycle.” Lists April 12, 2010 as the start date for .NET Framework 4.0. Official documentation. ↩
- Jake Archibald, “Abortable fetch,” 2017, including “The history.” Author's article. ↩
- WHATWG, whatwg/fetch issue #27, “Aborting a fetch,” opened March 26, 2015. The issue body also links to earlier discussion. Issue. ↩
- ECMA-262, sixth edition, 2015, §25.4 “Promise Objects.” Historical standard. ↩
- Microsoft, “Cancellation in Managed Threads.” The current .NET contract for requesting, observing, and cleaning up cancellation. Official documentation. ↩
- WHATWG DOM, §3 “Aborting ongoing activities.” Standard. ↩
- WHATWG Fetch,
fetch()and abort algorithms. Standard. ↩ - React, “Fetching data with Effects.” Official documentation. ↩