Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7c709b4

Browse files
committed
Document how to cancel an asynchronous task group.
1 parent d343f97 commit 7c709b4

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Doc/library/asyncio-task.rst

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,44 @@ reported by :meth:`asyncio.Task.cancelling`.
414414
Improved handling of simultaneous internal and external cancellations
415415
and correct preservation of cancellation counts.
416416

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+
417455
Sleeping
418456
========
419457

0 commit comments

Comments
 (0)