Cancellation¶
Cancellation is cooperative, as in .NET. A CancellationTokenSource owns the state, its token is handed to the
work, and the work checks it or registers a callback. Nothing is interrupted from outside, because Python cannot
stop a running thread.
Cancel running work¶
from flpit.task import CancellationToken, CancellationTokenSource, OperationCanceledError, Task
def work(token: CancellationToken) -> None:
while True:
token.throw_if_cancellation_requested() # the cooperative check
time.sleep(0.01)
cts = CancellationTokenSource()
running = Task.run(work, cts.token)
cts.cancel() # or cts.cancel_after(seconds) for a timeout
try:
running.result()
except OperationCanceledError:
pass
assert running.status == "cancelled"
throw_if_cancellation_requested() raises OperationCanceledError when the token has been cancelled. A task
that ends that way has the status "cancelled". Use cts.cancel_after(seconds) instead of cancel() for a
timeout.
result() and await on a cancelled task raise OperationCanceledError. task.wait() and Task.wait_all() raise
one AggregateError instead, as .NET does.
Run code on cancellation¶
log: list[str] = []
cts = CancellationTokenSource()
registration = cts.token.register(lambda: log.append("cleanup")) # runs when cancelled
cts.cancel()
assert log == ["cleanup"]
register returns a registration you can dispose to unsubscribe.
Combine tokens¶
A linked source is cancelled as soon as any of its tokens is:
user = CancellationTokenSource()
timeout = CancellationTokenSource()
either = CancellationTokenSource.create_linked_token_source(user.token, timeout.token)
timeout.cancel()
assert either.token.is_cancellation_requested # cancelled by whichever fires first
Where tokens are accepted¶
Most blocking and awaiting APIs take one: Task.delay(seconds, token=...), Task.wait_all and Task.wait_any,
SemaphoreSlim.wait and wait_async, channel reads and writes, and the terminal operators of
AsyncFlpIt.