@@ -414,6 +414,44 @@ reported by :meth:`asyncio.Task.cancelling`.
414
414
Improved handling of simultaneous internal and external cancellations
415
415
and correct preservation of cancellation counts.
416
416
417
+ Group Cancellation
418
+ ------------------
419
+
420
+ Cancelling an entire task group is not natively supported by the standard
421
+ library but can be achieved by adding a task to the group that raises an
422
+ exception and ignoring that exception:
423
+
424
+ .. code-block :: python
425
+
426
+ import asyncio
427
+ from asyncio import TaskGroup
428
+
429
+ class CancelTaskGroup (Exception ):
430
+ """ Exception raised to cancel a task group."""
431
+
432
+ async def job (task_id , sleep_time ):
433
+ print (f ' { task_id} : start ' )
434
+ await asyncio.sleep(sleep_time)
435
+ print (f ' { task_id} : done ' )
436
+
437
+ async def cancel_task_group ():
438
+ """ A task that would cancel the group it belongs to."""
439
+ raise CancelTaskGroup()
440
+
441
+ async def main ():
442
+ try :
443
+ async with TaskGroup() as group:
444
+ # ... spawn some tasks ...
445
+ group.create_task(job(1 , 1 ))
446
+ group.create_task(job(2 , 2 ))
447
+ # create a task that would cancel the group after 1.5 seconds
448
+ await asyncio.sleep(1.5 )
449
+ group.create_task(cancel_task_group())
450
+ except * CancelTaskGroup:
451
+ pass
452
+
453
+ asyncio.run(main())
454
+
417
455
Sleeping
418
456
========
419
457
0 commit comments