Search code examples
pythonasync-awaitpython-asyncio

How to await a list of tasks in python?


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

Solution

  • 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()