Search code examples
pythonevent-looppython-asyncio

asyncio task cancel. Is is synchronous?


I understand that task.cancel() arranges an exception to be thrown inside the task function. Is that happen in a synchronous way? (As I don't await task.cancel()). Can code that follows the line task.cancel() assume that the task will no longer run?

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()

Solution

  • Can code that follows the line task.cancel() assume that the task will no longer run?

    No. task.cancel() only marks task to be cancelled later. You should explicitly await task after it and catch CancelledError to be sure task is cancelled.

    See example here.