"""演示取消时的清理,以及 asyncio.shield 保护关键任务。""" from __future__ import annotations import asyncio from contextlib import suppress async def critical(cleanup: list[str]) -> str: try: await asyncio.sleep(0.05) cleanup.append("done") return "critical" except asyncio.CancelledError: cleanup.append("cancelled") raise async def without_shield() -> list[str]: cleanup: list[str] = [] task = asyncio.create_task(critical(cleanup)) await asyncio.sleep(0.01) task.cancel() with suppress(asyncio.CancelledError): await task return cleanup async def with_shield() -> tuple[list[str], str]: cleanup: list[str] = [] inner = asyncio.create_task(critical(cleanup)) async def outer() -> None: try: await asyncio.shield(inner) except asyncio.CancelledError: cleanup.append("outer-cancelled") raise outer_task = asyncio.create_task(outer()) await asyncio.sleep(0.01) outer_task.cancel() with suppress(asyncio.CancelledError): await outer_task result = await inner return cleanup, result async def main() -> None: plain = await without_shield() shielded, result = await with_shield() print(f"without shield: {plain}") print(f"with shield: {shielded} {result}") if __name__ == "__main__": asyncio.run(main())