簡體   English   中英

方法基本完成后,AsyncIO任務不會結束

[英]AsyncIO task doesn't end when the method is essentially finished

我正在嘗試運行協程,並使用eventloop.run_until_complete等待其返回值,但是我注意到,在協程基本完成之后, run_until_complete返回了很多時間(它最終會返回)。

這是我嘗試過的片段:

def wait_for_message(timeout_sec):
    loop = asyncio.get_event_loop()
    fut = asyncio.ensure_future(_receive_pb_msgs(timeout_sec))
    res = loop.run_until_complete(fut)

    return res

async def _receive_msgs(timeout_sec):
    start_time = time()
    current_time = start_time
    text = None
    async with wsc.connect("URL") as ws:
        while current_time - start_time <= timeout_sec:
            jdata = await ws.recv()
            msg = json.loads(jdata)
            if some_criteria:
                text = msg
                break

            current_time = time()
            await sleep(.1)
    print(f"return: {current_time - start_time}")
    return text


if __name__ == "__main__":
    s = time()
    msg = wait_for_message(10)
    e = time()
    print(f"actual: {e - s})

和輸出:

return: 6.387637138366699
actual: 38.61859059333801

如您所見,即使功能在6秒鍾后完成,循環仍需要38秒鍾才能完成。

我在這里想念什么嗎? 謝謝!

  1. breaksome_criteria將離開current_time過時的(因為當前的迭代不會予以考慮)
  2. 上次存儲current_time之后,可能會發生一些async with退出清理的async with操作

您絕對應該在打印return:之前放置current_time = time()行。 它可能會修復差異。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM