|
| 1 | +# Test cancelling a task |
| 2 | + |
| 3 | +try: |
| 4 | + import asyncio |
| 5 | +except ImportError: |
| 6 | + print("SKIP") |
| 7 | + raise SystemExit |
| 8 | + |
| 9 | + |
| 10 | +async def task(s, allow_cancel): |
| 11 | + try: |
| 12 | + print("task start") |
| 13 | + await asyncio.sleep(s) |
| 14 | + print("task done") |
| 15 | + except asyncio.CancelledError as er: |
| 16 | + print("task cancel") |
| 17 | + if allow_cancel: |
| 18 | + raise er |
| 19 | + |
| 20 | + |
| 21 | +async def task2(allow_cancel): |
| 22 | + print("task 2") |
| 23 | + try: |
| 24 | + await asyncio.create_task(task(0.05, allow_cancel)) |
| 25 | + except asyncio.CancelledError as er: |
| 26 | + print("task 2 cancel") |
| 27 | + raise er |
| 28 | + print("task 2 done") |
| 29 | + |
| 30 | + |
| 31 | +async def main(): |
| 32 | + # Cancel task immediately |
| 33 | + t = asyncio.create_task(task(2, True)) |
| 34 | + print(t.cancel()) |
| 35 | + |
| 36 | + print("main checking task is cancelled", t.cancelled()) |
| 37 | + |
| 38 | + # Cancel task after it has started |
| 39 | + t = asyncio.create_task(task(2, True)) |
| 40 | + await asyncio.sleep(0.01) |
| 41 | + print(t.cancel()) |
| 42 | + print("main sleep") |
| 43 | + await asyncio.sleep(0.01) |
| 44 | + |
| 45 | + print("main checking task is cancelled", t.cancelled()) |
| 46 | + |
| 47 | + # Cancel task multiple times after it has started |
| 48 | + t = asyncio.create_task(task(2, True)) |
| 49 | + await asyncio.sleep(0.01) |
| 50 | + for _ in range(4): |
| 51 | + print(t.cancel()) |
| 52 | + print("main sleep") |
| 53 | + await asyncio.sleep(0.01) |
| 54 | + |
| 55 | + print("main checking task is cancelled", t.cancelled()) |
| 56 | + |
| 57 | + # Await on a cancelled task |
| 58 | + print("main wait") |
| 59 | + try: |
| 60 | + await t |
| 61 | + except asyncio.CancelledError: |
| 62 | + print("main got CancelledError") |
| 63 | + |
| 64 | + # Cancel task after it has finished |
| 65 | + t = asyncio.create_task(task(0.01, False)) |
| 66 | + await asyncio.sleep(0.05) |
| 67 | + print(t.cancel()) |
| 68 | + |
| 69 | + print("main checking task is cancelled", t.cancelled()) |
| 70 | + |
| 71 | + # Nested: task2 waits on task, task2 is cancelled (should cancel task then task2) |
| 72 | + print("----") |
| 73 | + t = asyncio.create_task(task2(True)) |
| 74 | + await asyncio.sleep(0.01) |
| 75 | + print("main cancel") |
| 76 | + t.cancel() |
| 77 | + print("main sleep") |
| 78 | + await asyncio.sleep(0.1) |
| 79 | + |
| 80 | + print("main checking task 2 is cancelled", t.cancelled()) |
| 81 | + |
| 82 | + |
| 83 | +asyncio.run(main()) |
0 commit comments