Asyncio Cancel Propagation Graceful

Propagate cancellation through async tasks with cleanup for graceful shutdown.

PythonResilience

Code

pythonsnippet
19 lines
import asyncio

async def worker(name, stop_event):
    try:
        while not stop_event.is_set():
            await asyncio.sleep(1)
            print(f'{name} working')
    except asyncio.CancelledError:
        print(f'{name} cleaning up')
        raise

async def main():
    stop = asyncio.Event()
    tasks = [asyncio.create_task(worker(f'w{i}', stop)) for i in range(3)]
    await asyncio.sleep(5)
    stop.set()
    for t in tasks:
        t.cancel()
    await asyncio.gather(*tasks, return_exceptions=True)

How it works

Structurally, expect the functions worker and main and nothing else.

Iteration happens inside while not stop_event.is_set() — everything outside it runs once. Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. async appears at a raise inside an except handler — it fires only while that failure type is already being handled.

Points of care

  • Plan for an install step: asyncio is a real dependency, resolved by the package manager.

Putting it to use

The main signature reads def worker(name, stop_event)

Callers only need worker — everything else stays internal.

Core lines

async def worker(name, stop_event):
    try:
        while not stop_event.is_set():
            await asyncio.sleep(1)
            print(f'{name} working')
    except asyncio.CancelledError:
        print(f'{name} cleaning up')
        raise
async def main():
    stop = asyncio.Event()
    tasks = [asyncio.create_task(worker(f'w{i}', stop)) for i in range(3)]
    await asyncio.sleep(5)
    stop.set()
    for t in tasks:
        t.cancel()
    await asyncio.gather(*tasks, return_exceptions=True)

Interactive Tools for This Topic

FAQ

When is the exception raised?
Inside an `except` handler — the `async` fires only while that failure type is already being handled, not on its own trigger.
Do I need to install anything before running this?
Yes: `asyncio` must be present in the project or the import fails at load time.