@@ -342,6 +342,25 @@ and reliable way to wait for all tasks in the group to finish.
342342
343343 Close the given coroutine if the task group is not active.
344344
345+ .. method :: stop()
346+
347+ Stop the task group
348+
349+ :meth: `~asyncio.Task.cancel ` will be called on any tasks in the group that
350+ aren't yet done, as well as the parent (body) of the group. This will
351+ cause the task group context manager to exit *without * a
352+ :exc: `asyncio.CancelledError ` being raised.
353+
354+ If :meth: `stop ` is called before entering the task group, the group will be
355+ stopped upon entry. This is useful for patterns where one piece of
356+ code passes an unused TaskGroup instance to another in order to have
357+ the ability to stop anything run within the group.
358+
359+ :meth: `stop ` is idempotent and may be called after the task group has
360+ already exited.
361+
362+ .. versionadded :: 3.14
363+
345364Example::
346365
347366 async def main():
@@ -414,53 +433,6 @@ reported by :meth:`asyncio.Task.cancelling`.
414433 Improved handling of simultaneous internal and external cancellations
415434 and correct preservation of cancellation counts.
416435
417- Terminating a Task Group
418- ------------------------
419-
420- While terminating a task group is not natively supported by the standard
421- library, termination can be achieved by adding an exception-raising task
422- to the task group and ignoring the raised exception:
423-
424- .. code-block :: python
425-
426- import asyncio
427- from asyncio import TaskGroup
428-
429- class TerminateTaskGroup (Exception ):
430- """ Exception raised to terminate a task group."""
431-
432- async def force_terminate_task_group ():
433- """ Used to force termination of a task group."""
434- raise TerminateTaskGroup()
435-
436- async def job (task_id , sleep_time ):
437- print (f ' Task { task_id} : start ' )
438- await asyncio.sleep(sleep_time)
439- print (f ' Task { task_id} : done ' )
440-
441- async def main ():
442- try :
443- async with TaskGroup() as group:
444- # spawn some tasks
445- group.create_task(job(1 , 0.5 ))
446- group.create_task(job(2 , 1.5 ))
447- # sleep for 1 second
448- await asyncio.sleep(1 )
449- # add an exception-raising task to force the group to terminate
450- group.create_task(force_terminate_task_group())
451- except * TerminateTaskGroup:
452- pass
453-
454- asyncio.run(main())
455-
456- Expected output:
457-
458- .. code-block :: text
459-
460- Task 1: start
461- Task 2: start
462- Task 1: done
463-
464436Sleeping
465437========
466438
0 commit comments