cancel-async-tasks
Cancel Async Tasks
Overview
This skill provides guidance for implementing robust asyncio task cancellation in Python, particularly when dealing with signal handling (SIGINT/KeyboardInterrupt), semaphore-based concurrency limiting, and ensuring proper cleanup of all tasks including those waiting in queues.
Key Concepts
Signal Propagation in Asyncio
Understanding how signals interact with asyncio is critical:
-
KeyboardInterrupt vs CancelledError: When SIGINT is received during
asyncio.run(), the behavior differs from catching exceptions inside async code. The event loop typically converts the interrupt toCancelledErrorthat propagates through tasks. -
Signal handler context: Signal handlers run in the main thread, but asyncio tasks may be in various states (running, waiting on semaphore, waiting on I/O).
-
Event loop state: The event loop's handling of SIGINT depends on whether it's running
asyncio.run()vs manual loop management.