asyncio

来自百合仙子's Wiki
跳转到导航 跳转到搜索

中断任务

[1]

  • 使用 asyncio.gather 而不是 asyncio.wait
  • 在中断时取消任务,然后继续:
      loop = asyncio.get_event_loop()
      task = loop.create_task(run(loop))
      try:
        loop.run_until_complete(task)
      except KeyboardInterrupt:
        task.cancel()
        try:
          loop.run_until_complete(task)
        except asyncio.CancelledError:
          pass
      finally:
        loop.close()
    
  • 记得在被取消时关闭连接、处理被取消的异常等

参考资料