2

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()
user3599803
  • 6,435
  • 17
  • 69
  • 130
  • 1
    From reading the documentation I would say no, it says "This arranges for a CancelledError exception to be thrown into the wrapped coroutine on the next cycle of the event loop." – Fredrik Jul 18 '19 at 07:53

1 Answers1

2

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.

Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159