如何强制 asyncio 任务到 运行?

How can I force asyncio task to run?

我注意到,当我使用 create_task 生成异步任务时,它首先完成其余逻辑,而不是启动该任务。我被迫添加一个 await asyncio.sleep(0) 来启动任务,这对我来说似乎有点古怪和不干净。

这是一些示例代码:

async def make_rpc_calls(...some args...)
  val_1, val_2 = await asyncio.gather(rpc_call_1(...), rpc_call_2(...))
  return process(val_1, val_2)

def some_very_cpu_intensive_function(...some args...):
  // Does a lot of computation, can take 20 seconds to run
  
task_1 = asyncio.get_running_loop().create_task(make_rpc_calls(...))
intensive_result = some_very_cpu_intensive_function(...)
await task_1
process(intensive_result, task_1.result())

任何时候我 运行 以上,它 运行 在启动昂贵的 RPC 之前是 some_very_cpu_intensive_function 函数。我让这个工作的唯一方法是:

async def make_rpc_calls(...some args...)
  val_1, val_2 = await asyncio.gather(rpc_call_1(...), rpc_call_2(...))
  return process(val_1, val_2)

def some_very_cpu_intensive_function(...some args...):
  // Does a lot of computation, can take 20 seconds to run

task_1 = asyncio.get_running_loop().create_task(make_rpc_calls(...))

await asyncio.sleep(0)

intensive_result = some_very_cpu_intensive_function(...)
await task_1
process(intensive_result, task_1.result())

这对我来说感觉像是一个 hack - 我强制事件循环进行上下文切换,并且感觉我没有正确使用 asyncio 框架。我应该用另一种方法来解决这个问题吗?

sleep() always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

来源:https://docs.python.org/3/library/asyncio-task.html