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()
永远不会等待任何东西。
(在我的实际问题中,我有一个阻塞调用,如果任务已经取消,我不想运行该调用。但任务永远不会被取消,因为它们正在运行)。
如何使其并发?
哎呀,这在我的 MRE 中有效
await asyncio.sleep(0)