如何将控制权交还给事件循环

问题描述 投票:0回答:1
import asyncio

async def long_running_task():
    try:
        while True:
            # Your long-running processing
            if asyncio.current_task().cancelled():
                raise asyncio.CancelledError
    except asyncio.CancelledError:
        print("Task was cancelled")

async def main():
    task = asyncio.create_task(long_running_task())
    await asyncio.sleep(5)  # Let the task run for 5 seconds
    task.cancel()  # Cancel the task
    print("cancelled")

asyncio.run(main())

task.cancel()
永远不会被调用,因为它是单线程的并且
long_running_task()
永远不会等待任何东西。

(在我的实际问题中,我有一个阻塞调用,如果任务已经取消,我不想运行该调用。但任务永远不会被取消,因为它们正在运行)。

如何使其并发?

python-asyncio
1个回答
0
投票

哎呀,这在我的 MRE 中有效

await asyncio.sleep(0)
© www.soinside.com 2019 - 2024. All rights reserved.