Asyncio.Task.All_Tasks()的不同行为 [英] Different behaviour of asyncio.Task.all_tasks()
本文介绍了Asyncio.Task.All_Tasks()的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
第一个示例:
import asyncio
async def req():
print('request')
await asyncio.sleep(1)
async def run():
print(len(asyncio.Task.all_tasks()))
asyncio.ensure_future(req())
print(len(asyncio.Task.all_tasks()))
await asyncio.sleep(2)
print(len(asyncio.Task.all_tasks()))
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
结果为:
1
2
request
1
第二个示例:
import asyncio
async def req():
print('request')
await asyncio.sleep(1)
async def run():
print(len(asyncio.Task.all_tasks()))
t = asyncio.ensure_future(req())
print(len(asyncio.Task.all_tasks()))
await t
print(len(asyncio.Task.all_tasks()))
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
结果为:
1
2
request
2
那么,为什么在第一个示例中最后一个调用asyncio.Task.all_asks()返回1,而在第二个示例中返回2? 换句话说,为什么在第一个示例中,任务、WRAP()请求从事件循环所有任务集中被删除,以及为什么对于第二个示例不是这样。
推荐答案
任务在destroyed时从all_tasks()
中删除。
添加del
语句:
[...]
await t
del t
print(len(asyncio.Task.all_tasks()))
它将产生:
1
2
request
1
这篇关于Asyncio.Task.All_Tasks()的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文