Sub topic 5
How task cancellation works
This chapter covers what Task.cancel() does, when the cancellation takes effect, and how a task ends up in the cancelled state. It assumes you can create tasks with asyncio.create_task and read try/finally. Writing cleanup code for cancellation is the next chapter's topic. Here the focus is the mechanism.
Cancellation is a request
task.cancel() does not stop a task. It asks the event loop to raise asyncio.CancelledError inside the task's coroutine at the point where it is currently suspended, which is the await it is waiting on. The task then runs on its own, unwinding through finally blocks and context managers, and usually ends when the exception leaves the coroutine.
Three consequences follow:
cancel()returns immediately. The task has not finished when the call returns.- The task only sees the cancellation at an
await. Code between awaits runs to completion first. - The task decides what happens next. It can let the error propagate, which is the normal case, or it can catch it and carry on.
Run this example:
import asyncio
async def worker():
try:
while True:
print("tick")
await asyncio.sleep(0.1)
finally:
print("worker: finally ran")
async def main():
task = asyncio.create_task(worker())
await asyncio.sleep(0.25)
print("cancel() returned", task.cancel())
print("cancelled yet?", task.cancelled())
try:
await task
except asyncio.CancelledError:
print("after await, task.cancelled():", task.cancelled())
asyncio.run(main())The output is three tick lines, then cancel() returned True, then cancelled yet? False. Next comes worker: finally ran, and last after await, task.cancelled(): True.
The False shows that the worker has not yet seen the error when cancel() returns. The worker only reacts after main awaits and gives the loop a chance to run it.
The sequence of events
Two details matter here. First, a task that is cancelled while waiting on another task or future passes the request along. The inner object is cancelled, and the outer task sees the error when the inner one finishes cancelling. Second, whoever awaits a cancelled task gets CancelledError raised at their own await. Cancellation travels up through awaiting code like any exception.
What `cancel()` returns
cancel() returns a boolean. It tells you whether the request was accepted, not whether the task will end up cancelled.
| Task state when `cancel()` is called | Return value | Effect |
|---|---|---|
| Created, not yet started | `True` | The coroutine body never runs. |
| Suspended at an `await` | `True` | `CancelledError` is raised there on the next loop step. |
| Already done (result, exception, or cancelled) | `False` | Nothing happens. |
Cancelling before the first step is easy to miss:
import asyncio
async def never_runs():
print("this line is never printed")
async def main():
task = asyncio.create_task(never_runs())
task.cancel() # the loop has not had a chance to start the task yet
try:
await task
except asyncio.CancelledError:
print("cancelled =", task.cancelled())
done = asyncio.create_task(asyncio.sleep(0))
await done
print("cancel() on a finished task:", done.cancel())
asyncio.run(main())This prints cancelled = True and then cancel() on a finished task: False.
Reading the final state
After cancellation finishes, three methods describe the task:
task.done()isTrue.task.cancelled()isTrueonly if the task ended becauseCancelledErrorleft its coroutine.task.result()andtask.exception()raiseCancelledErrorfor a cancelled task. They do not return anything.
Check cancelled() before calling exception(). A common bug is calling task.exception() in a "done" callback and crashing on cancelled tasks.
You can attach a message with task.cancel(msg="shutting down"). The message becomes the argument of the CancelledError the task sees, which helps when you need to tell several cancellation sources apart in logs.
A task can refuse to be cancelled
Because cancellation is delivered as an exception, the task can catch it. If it does and returns normally, the task finishes with a result and cancelled() is False:
import asyncio
async def stubborn():
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
print("stubborn: ignoring the cancellation")
return "finished anyway"
async def main():
task = asyncio.create_task(stubborn())
await asyncio.sleep(0.1)
task.cancel()
print(await task)
print("cancelled():", task.cancelled())
asyncio.run(main())The output is stubborn: ignoring the cancellation, then finished anyway, then cancelled(): False.
Cancellation passes through awaited tasks
When task A is awaiting task B and you cancel A, asyncio cancels B too. A's pending await is on B, so the request is forwarded:
import asyncio
async def inner():
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
print("inner: received CancelledError")
raise
async def outer():
try:
await asyncio.create_task(inner())
except asyncio.CancelledError:
print("outer: received CancelledError")
raise
async def main():
task = asyncio.create_task(outer())
await asyncio.sleep(0.1)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("main: outer task is cancelled")
asyncio.run(main())The inner task reports first, then the outer, then main. Compare this with a task that was started with create_task and never awaited by its creator. Cancelling the creator does not cancel that task, because the creator was not waiting on it. This is why detached tasks outlive their parents, and why the structured concurrency chapters exist.
Details that cause surprises
CancelledError is not an Exception. Since Python 3.8 it inherits from BaseException, so except Exception: does not catch it. A bare except: or except BaseException: does, and will swallow cancellations by accident.
Cancellation needs an await. A coroutine that runs a long loop or heavy computation without awaiting never gives the loop a chance to deliver the error, so cancel() has no visible effect until the next suspension. To make such code cancellable, put an await asyncio.sleep(0) at sensible points or move the work to a thread or process.
Cancelling a thread does not work either. If a task awaits asyncio.to_thread(...), cancelling the task stops the waiting. The thread keeps running to completion.
A second cancel() on a task that is still unwinding also returns True. It requests another cancellation, so a task that is in the middle of cleanup can be interrupted again at its next await. Keep cleanup short and avoid awaiting things that can hang.
The event loop does not hold strong references to tasks, which is why you keep your own. asyncio.run cancels any tasks still pending when the main coroutine returns and waits for them to finish, but it is better to cancel and await your tasks yourself.
Summary of the model
cancel()records a request and returnsTrueif the task was not already done.- At the next loop step,
CancelledErroris raised at the task's pendingawait. - The task unwinds. If the error leaves the coroutine, the task becomes cancelled.
- Anyone awaiting that task gets
CancelledErrorat their ownawait.
Exercise
A task is running while True: x += 1 with no await inside. Another task calls worker.cancel() and then awaits it. What happens, and why?
Show answer
The cancellation request is recorded, but CancelledError can only be raised at an await. The worker never suspends, so it never yields to the event loop. In fact, the task that called cancel() can never run again either, because the loop is stuck inside the worker. The program hangs. The fix is to add an await (for example await asyncio.sleep(0)) in the loop, or to move the CPU-bound work to a thread or process.
Exercise
A task catches CancelledError, prints a message, and returns the string "done" without re-raising. After task.cancel() and await task, what are the value of the await expression and the value of task.cancelled()?
Show answer
The await expression evaluates to "done", and task.cancelled() is False. The task ended with a normal result, so asyncio does not mark it as cancelled. The code that requested the cancellation was ignored.
Exercise
You call task.cancel() on a task that has already returned a result. What does the call return, and does the task become cancelled?
Show answer
It returns False, and the task stays finished with its original result. cancel() has no effect on a task that is already done.