运行 在线程中运行 class 在后台使用 asyncio

Running functions in a thread class in the background with asyncio

这是我第一次尝试在项目中使用 asyncio。我想让我的 class 初始化并 运行,它的几个函数 运行 定期 "in the background"。我希望 class' 在启动这些后台任务后初始化为 return,这样它就可以同时继续执行同步操作。

我有:

 class MyClass(threading.Thread):
  def __init__(self, param):
      self.stoprequest = threading.Event()
      threading.Thread.__init__(self)

      self.param = param

      self.loop = asyncio.new_event_loop()
      asyncio.set_event_loop(self.loop)
      asyncio.ensure_future(self.periodic(), loop=self.loop)

      print("Initialized")

  async def periodic(self):
      while True:
          print("I'm here")
          await asyncio.sleep(1)

  def run(self):
       # continue to do synchronous things

不出所料,这行不通。我也尝试过在 init 中使用 "normal" asyncio 函数和 run_until_complete(),但当然 init 永远不会 returns 然后。

我怎样才能 运行 asyncio 属于此 class 的函数在后台周期性地运行,而其余的 class (run())继续做同步工作?

将循环作为参数传递给 ensure_future 不会启动此循环。您应该调用 run_until_completerun_forever 来强制启动协程,没有其他方法可以做到这一点。

How can I run asyncio functions that belong to this class periodically in the background, while the rest of the class (run()) continues to do synchronous work?

你不能。就像你不能在主线程中同时 运行 事件循环和同步代码一样。 Loop starting - 阻塞线程的执行流直到循环停止。这就是 asyncio 的工作原理。

如果你想 运行 asyncio 在后台,你应该 运行 它在单独的线程中,并在主线程中执行同步操作。可以在 .

中找到如何操作的示例

你需要 运行 在线程中阻塞代码以及 asyncio 现在最方便的方法是在主线程中 运行 asyncio 和 运行 使用 run_in_executor 函数在后台线程中阻塞代码。你可以找到这样做的例子 .

重要的是要说 asyncio 本身通常用于主线程(没有其他线程)以实现异步编程的好处。你确定你需要第二个线程吗?如果不是,请阅读 以了解为什么使用 asyncio