【发布时间】:2021-10-07 20:08:05
【问题描述】:
看着asyncio docs,我遇到了这个例子
async def main():
# Create a "cancel_me" Task
task = asyncio.create_task(cancel_me())
# Wait for 1 second
await asyncio.sleep(1)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("main(): cancel_me is cancelled now")
asyncio.run(main())
task.cancel()之后,做await task的目的是什么?如果它曾经被屏蔽取消,这是等待未来完成吗?
换句话说,为什么不呢:
async def main():
# Create a "cancel_me" Task
task = asyncio.create_task(cancel_me())
# Wait for 1 second
await asyncio.sleep(1)
task.cancel()
asyncio.run(main())
【问题讨论】:
-
重点是任务已经取消,不能再等待了。示例代码将打印错误。屏蔽任务将继续运行,但也会抛出 CancelledError。
标签: python python-3.x python-asyncio future