227. Efficient Task Cancellation in Asyncio
🔹 1. Basic Task Cancellation
import asyncio
async def long_task():
print("Task started")
try:
await asyncio.sleep(5)
except asyncio.CancelledError:
print("Task was cancelled")
raise
async def main():
task = asyncio.create_task(long_task())
await asyncio.sleep(2) # Wait for a while
task.cancel() # Cancel the task
try:
await task
except asyncio.CancelledError:
print("Handled cancellation")
asyncio.run(main())🔹 2. Task Cancellation with Timeout
🔹 3. Canceling Multiple Tasks in a Group
🔹 4. Cancelling Task with Cleanup
🔹 5. Handling Cancellation in Long-Running Loops
🔹 6. Using asyncio.shield() to Prevent Task Cancellation
asyncio.shield() to Prevent Task Cancellation🔹 7. Canceling Tasks in a Context Manager
🔹 8. Task Cancellation with CancelledError Handling
🔹 9. Handling Task Cancellation in Multiple Coroutine Functions
🔹 10. Task Cancellation with Custom Timeout
💡 Best Practices for Efficient Task Cancellation:
Last updated