In .Net C#, there is a function Task.WhenAll
that can take a list of tasks to await them. What should I use in python? I am trying to do the same with this:
tasks = ... # list of coroutines
for task in tasks:
await task
After adding tasks to a list, you should use asyncio.gather
that gives coroutines as an argument list and executes them asynchronously. Also, you could use asyncio.create_task
that takes a coroutine and calls concurrent tasks in the event loop.
import asyncio
async def coro(i):
await asyncio.sleep(i//2)
async def main():
tasks = []
for i in range(5):
tasks.append(coro(i))
await asyncio.gather(*tasks)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
Use asyncio.gather
if you're on Python 3.7 or above. From the docs:
Run awaitable objects in the aws sequence concurrently. If any awaitable in aws is a coroutine, it is automatically scheduled as a Task. If all awaitables are completed successfully, the result is an aggregate list of returned values. The order of result values corresponds to the order of awaitables in aws.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With