简体   繁体   English

异步任务取消。 是同步的吗?

[英]asyncio task cancel. Is is synchronous?

I understand that task.cancel() arranges an exception to be thrown inside the task function.我知道task.cancel()安排在任务函数内部抛出异常。 Is that happen in a synchronous way?这是以同步方式发生的吗? (As I don't await task.cancel()). (因为我不等待 task.cancel())。 Can code that follows the line task.cancel() assume that the task will no longer run?跟在task.cancel()task.cancel()代码可以假设任务将不再运行吗?

A simple example:一个简单的例子:

async def task1():
    await asyncio.sleep(3)
    print("after sleep")

async def task2():
    t = loop.create_task(task1())
    await asyncio.sleep(1)
    t.cancel()
    # can the following code lines assume that task1 is no longer running?

loop = asyncio.get_event_loop()
loop.run_forever()

Can code that follows the line task.cancel() assume that the task will no longer run?跟在 task.cancel() 行后面的代码可以假设任务将不再运行吗?

No. task.cancel() only marks task to be cancelled later. task.cancel()只标记稍后要取消的任务。 You should explicitly await task after it and catch CancelledError to be sure task is cancelled.您应该在它之后显式等待任务并捕获CancelledError以确保任务被取消。

See example here .请参阅此处的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM