Clear an interrupted event loop without closing th

2019-08-06 02:12发布

Try the following code:

import asyncio

async def fun1():
    #block
    await asyncio.sleep(10)

loop = asyncio.get_event_loop()
count = 0
while count < 10:
    count += 1
    print(count)
    try:
        fut = asyncio.ensure_future(asyncio.wait_for(fun1(),1))
        loop.run_until_complete(fut)
    except:
        pass

And then inspect the tasks by asyncio.Task.all_tasks(loop=loop). You will see that all canceled/finished tasks are still bound to the loop. Instead of closing and getting a new loop, how can I keep the loop and only clear the finished/canceled tasks?

1条回答
贪生不怕死
2楼-- · 2019-08-06 02:43

Tasks are bound to loop with weakref, it means they will be garbage collected on next gc run if no references to them exists:

import asyncio
import gc


def main():
    #  your code here
main()


print('Before gc:', asyncio.Task.all_tasks())

gc.collect()

print('After gc:', asyncio.Task.all_tasks())

You'll see empty set after gc run.

查看更多
登录 后发表回答