Asyncio Shield Critical Section

Protect critical sections from cancellation with asyncio.shield for atomic operations.

PythonResilience

Code

pythonsnippet
22 lines
import asyncio

async def critical_operation():
    await asyncio.sleep(2)
    return 'done'

async def handler():
    try:
        result = await asyncio.shield(critical_operation())
        return result
    except asyncio.CancelledError:
        print('handler cancelled, critical still running')
        raise

async def main():
    task = asyncio.create_task(handler())
    await asyncio.sleep(0.5)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        pass

How it works

Asyncio Shield Critical Section keeps everything in the functions critical_operation, handler and main.

Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. A async is raised inside an except block, so it is conditional on that failure being handled in the first place.

What to watch for

  • Dependency check: asyncio — not built-in, must be present in the project.

Applying it

The main signature reads def critical_operation()

Output lines are prefixed (handler cancelled, critical still running), making each step’s effect easy to spot.

Treat critical_operation as the API: import it, and ignore the supporting code.

Statements that matter

async def critical_operation():
    await asyncio.sleep(2)
    return 'done'
except asyncio.CancelledError:
    print('handler cancelled, critical still running')
    raise
except asyncio.CancelledError:
    pass

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.
Does this require external packages?
Yes — `asyncio`. Add it to your project before running the snippet.