3

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
Artyom Vancyan
  • 5,029
  • 3
  • 12
  • 34

2 Answers2

5

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()
Artyom Vancyan
  • 5,029
  • 3
  • 12
  • 34
  • 1
    Looks good, I will try it. Can you also explaine what does '*' stands for? – Ernest Rutherford Jun 12 '22 at 09:09
  • 1
    In short, `asyncio.gather(*tasks)` is the same as `asyncio.gather(coro(0), coro(1), coro(2), coro(3), coro(4))`. See [this](https://stackoverflow.com/questions/3941517/converting-list-to-args-when-calling-function). – Artyom Vancyan Jun 12 '22 at 09:26
0

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.

aIKid
  • 26,968
  • 4
  • 39
  • 65