在这种情况下,
Future一旦它真正开始运行,就无法取消它,因为您依赖的行为
concurrent.futures.Future,并且它的文档指出以下内容:
cancel()尝试取消呼叫。 如果该调用当前正在执行并且无法取消,则该方法将返回
False,否则,该调用将被取消并且该方法将返回True。
因此,唯一成功的取消操作是如果任务仍在中等待执行
Executor。现在,您实际上正在使用
asyncio.Future包裹
concurrent.futures.Future,并且在实践中,即使基础任务实际上已经在运行,如果您在调用后尝试
asyncio.Future返回,by
loop.run_in_executor()也会引发a
。但是,它 实际上 并不会取消中的任务执行。
CancellationError``yield from``cancel()__
Executor
如果需要实际取消任务,则需要使用更常规的方法来中断线程中正在运行的任务。具体操作方式取决于用例。对于示例中显示的用例,可以使用
threading.Event:
def blocking_func(seconds_to_block, event): for i in range(seconds_to_block): if event.is_set(): return print('blocking {}/{}'.format(i, seconds_to_block)) time.sleep(1) print('done blocking {}'.format(seconds_to_block))...event = threading.Event()blocking_future = loop.run_in_executor(None, blocking_func, 5, event)print('wait a few seconds!')yield from asyncio.sleep(1.5)blocking_future.cancel() # Mark Future as cancelledevent.set() # Actually interrupt blocking_func


