Run related tasks under a context manager.
Section: Tasks and Concurrency
Use TaskGroup for structured concurrency
python
python
import asyncio
async def worker(name, delay):
await asyncio.sleep(delay)
print(name)
async def main():
async with asyncio.TaskGroup() as tg:
tg.create_task(worker("a", 0.2))
tg.create_task(worker("b", 0.1))
asyncio.run(main())Explanation
Task groups provide a safer way to manage related tasks. If one task fails, the group cancels the rest and re-raises.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Tasks and Concurrency
Run tasks concurrently with gather
Wait for multiple coroutines and collect results.
Collect exceptions with gather
Keep other tasks running even if one fails.
Wait until the first task completes
Use `asyncio.wait()` to control waiting behavior.
Consume results as tasks finish
Process faster tasks first using `as_completed()`.
Run an async entrypoint
Execute a top-level coroutine and manage the event loop automatically.