asyncio-等待动态列表中的每个任务完成或被取消 [英] asyncio - wait for each task in a dynamic list to finish or be cancelled
问题描述
我有一个异步任务列表: [task1,task2,task3]
.每个任务都可以将更多任务添加到此列表中,例如, task3
可以添加 task4
.
I have a list of asyncio tasks: [task1, task2, task3]
. And each task can append more tasks to this list, e.g., task3
might append task4
.
如何等待此动态列表中的所有任务完成或被取消?
How can I wait for all tasks in this dynamic list to finish or be cancelled?
我尝试了 await asyncio.gather(* [task1,task2,task3])
,但是它不等待 task1
, task2创建的任务
或 task3
.
I tried await asyncio.gather(*[task1, task2, task3])
, but it doesn't wait for tasks created by task1
, task2
or task3
.
推荐答案
只要有未完成的任务,就可以使用循环来等待:
You can use a loop to wait for as long as there are unfinished tasks:
# create a list to hold the tasks
task_list = []
# you can pass task_list to coroutines that need to submit
# additional tasks
task_list.extend([task1, coro1(arg1, task_list), coro2(arg2, task_list)])
while task_list:
old_cnt = len(task_list)
await asyncio.gather(*task_list)
# we've finished the old set of tasks, but keep looping as long
# as some coroutines keep adding new ones
del task_list[:old_cnt]
task_list
的内容不必只是实际的 asyncio.Task
实例,该列表还可以包含协程对象或任何其他可等待的对象.您可以将 task_list
传递给需要将更多任务追加到列表的协程.一旦未添加新任务,调用 gather
后,任务列表将保持为空,并且循环将终止.
Contents of task_list
don't need to be just actual asyncio.Task
instances, the list can also contain coroutine objects or anything else that is awaitable. You can pass task_list
to the coroutines that need to append more tasks to the list. Once no new tasks have been added, the task list will remain empty after the call to gather
, and the loop will terminate.
这篇关于asyncio-等待动态列表中的每个任务完成或被取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!