Why CancellationTokenSource hangs an application
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
A CancellationTokenSource can hang an application when a cancellation callback registered via CancellationToken.Register() blocks, when cancellation is triggered on the UI thread causing a deadlock, or when Dispose() is called while callbacks are still executing. The most common pattern is a synchronous callback that tries to access a resource held by the thread calling Cancel(), creating a deadlock. Understanding that Cancel() executes registered callbacks synchronously on the calling thread is the key to avoiding these hangs.
How Cancel() Executes Callbacks
Cancel() does not return until every registered callback finishes. If any callback blocks, Cancel() blocks, and the calling code hangs.
Deadlock Scenario 1: Callback Waits on the Cancelling Thread
The callback runs on the same thread that called Cancel(), which already holds the lock. The callback waits for the lock, which will never be released.
Fix: Cancel Outside the Lock
Deadlock Scenario 2: UI Thread Synchronization Context
Fix: Use CancelAsync() (.NET 8+)
Fix: Cancel on a Background Thread
Deadlock Scenario 3: Dispose During Active Callbacks
Dispose() waits for callbacks to complete. If called from a different thread while callbacks are running, it blocks until they finish.
Fix: Cancel and Dispose Sequentially
Timeout-Based Cancellation Hang
Fix: Keep Callbacks Non-Blocking
Linked CancellationTokenSource
Debugging a Hanging Cancel
Common Pitfalls
- Blocking in cancellation callbacks:
Cancel()executes all registered callbacks synchronously on the calling thread. If a callback acquires a lock, waits on a task, or performs I/O, it blocksCancel()and can deadlock the application. Keep callbacks lightweight and non-blocking. - Calling
Cancel()while holding a lock: If any registered callback needs the same lock, you get a deadlock. Always callCancel()outside of lock blocks by copying theCancellationTokenSourcereference first. - Not disposing
CancellationTokenSource: UndisposedCancellationTokenSourceobjects leak timer handles (if timeout-based) and linked token registrations. Always dispose, preferably in afinallyblock. - Not disposing linked
CancellationTokenSource:CreateLinkedTokenSourceregisters a callback on the parent token. WithoutDispose(), this registration is never removed, causing a memory leak that grows over time. - Ignoring
AggregateExceptionfromCancel(): If a registered callback throws an exception,Cancel()wraps it in anAggregateExceptionand throws. Unhandled, this crashes the application. Always wrapCancel()in try-catch if callbacks might throw.
Summary
Cancel()executes all registered callbacks synchronously on the calling thread — blocking callbacks hangCancel()- Never call
Cancel()while holding a lock that callbacks need — moveCancel()outside the lock - Use
CancelAsync()(.NET 8+) orTask.Run(() => cts.Cancel())to avoid blocking the UI thread - Keep cancellation callbacks lightweight — offload heavy work to
Task.Run - Always dispose
CancellationTokenSource, especially linked token sources, to prevent memory leaks - Wrap
Cancel()in try-catch to handle exceptions from callbacks
Related reading
- Why can't asynchronous threads modify an ArrayList simultaneously?
- Why can't I use the 'await' operator within the body of a lock statement?
- Why ConcurrentHashMap cannot have a lock for each bucket?
- Why Do I have to worry about Thread Safety in CPython?
- Why can't I define a default constructor for a struct in .NET?
- Why can't I have abstract static methods in C?
- Why can't a 'continue' statement be inside a 'finally' block?
- Why can't I establish connection to rabbitMQ using python?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.