Method
phasync::cancel
Cancels a coroutine with a CancelledException.
Description#
public static phasync::cancel(
Fiber $fiber,
Stringable|CancelledException|string $message = 'Operation cancelled',
int $code = 0,
?Throwable $previous = null
): voidThe cancellation is sticky: every wait of the coroutine throws the CancelledException from then on, so a coroutine that catches it and waits again is cancelled again. It throws nothing in the caller: a coroutine that is not waiting meets it at its next wait, and one that cancels itself finishes its current step and meets it at its next wait too. A coroutine that ends with the exception it was cancelled with is no failure of the run, but awaiting it throws it. finally() callbacks are not cancelled.
It is a teardown, not a signal: to interrupt a wait once with an exception of your own, use phasync::throw. It cancels that coroutine only, not the coroutines it started; to cancel a whole tree, cancel its frame (Frame::cancel).
Parameters#
- $fiber Fiber
- A coroutine
- $message Stringable|CancelledException|string = 'Operation cancelled'
- The message of the CancelledException, or the CancelledException itself (such as a ShutdownException); another Throwable is refused, see
phasync::throw - $code int = 0
- The code of the CancelledException
- $previous ?Throwable = null
- What caused the cancellation
Errors / Exceptions#
| Exception | When |
|---|---|
InvalidArgumentException | If the coroutine has ended, or the message is a Throwable |
LogicException | If the coroutine was not started by phasync |
Examples#
phasync::run(function () {
$worker = phasync::go(function () {
try {
while (true) {
phasync::sleep(1);
}
} finally {
echo "cleaned up\n";
}
});
phasync::sleep(0.1);
phasync::cancel($worker);
try {
phasync::await($worker);
} catch (phasync\CancelledException) {
echo "cancelled\n";
}
});See also#
phasync::throwInterrupts one waitFrame::cancelCancels a framephasync::goStarts$fnas a coroutine in the current frame and scope, and returns it, without waiting for it.