Graceful asyncio Cancellation with Cleanup

Cancel running asyncio workers, catch CancelledError for cleanup, and report how many items were processed before shutdown.

PythonResilience

Code

pythonsnippet
51 lines
import asyncio
import random
from dataclasses import dataclass


@dataclass
class Worker:
    name: str
    processed: int = 0
    cleaned_up: bool = False

    async def run(self, queue: asyncio.Queue[int | None]) -> None:
        try:
            while True:
                item = await queue.get()
                try:
                    if item is None:
                        return
                    await asyncio.sleep(random.uniform(0.005, 0.02))
                    self.processed += 1
                finally:
                    queue.task_done()
        except asyncio.CancelledError:
            # Cancellation must propagate, but cleanup below still runs.
            raise
        finally:
            self.cleaned_up = True


async def main() -> None:
    queue: asyncio.Queue[int | None] = asyncio.Queue()
    for value in range(1, 31):
        queue.put_nowait(value)

    workers = [Worker(name=f"worker-{index}") for index in range(3)]
    tasks = [asyncio.create_task(worker.run(queue)) for worker in workers]

    await asyncio.sleep(0.02)
    for task in tasks:
        task.cancel()

    outcomes = await asyncio.gather(*tasks, return_exceptions=True)
    cancelled = sum(isinstance(item, asyncio.CancelledError) for item in outcomes)
    print(f"cancelled={cancelled} processed={sum(w.processed for w in workers)}")
    print(f"cleaned_up={all(w.cleaned_up for w in workers)}")
    print(f"pending={queue.qsize()}")


if __name__ == "__main__":
    asyncio.run(main())

What the code does

Graceful asyncio Cancellation with Cleanup is built around the class class and the functions run and main.

The cycling part of this snippet is while True. Await points sequence the coroutines; a failure lands where the result is consumed. The import line is the dependency contract: dataclass comes from asyncio and nothing else. finally appears at a raise inside an except handler — it fires only while that failure type is already being handled.

Watch out for

  • Requires asyncio as a package; the snippet will not run without it.

Applying it

The main signature reads def run(self, queue: asyncio.Queue[int | None]) -> None

The demo output is labeled (cleaned_up=, pending=), so every printed line maps back to its originating operation.

Launch the file; main takes over and steps through run.

Statements that matter

except asyncio.CancelledError:
    # Cancellation must propagate, but cleanup below still runs.
    raise
if item is None:
    return

Interactive Tools for This Topic

FAQ

When is the exception raised?
Inside an `except` handler — the `finally` fires only while that failure type is already being handled, not on its own trigger.
Which packages must be installed first?
Yes. The imports resolve to `asyncio`, which the package manager must provide.