CANCELTASK

Statement

Syntax

Asks a task to stop. The task stops at its next yield, and the code after that yield never runs.

CANCELTASK <handle>

Parts

<handle>A task handle: a variable filled by STARTTASK.

Good to know

  • The yields are Wait(), Sleep(), Sync(), Swap() and YieldTask(). A task that never yields cannot be stopped: it runs to its RETURN.
  • TaskCancelled() is true at once. AWAITTASK on the task then returns without an error, and TaskResult() raises an error.
  • On a task that already ended, CANCELTASK does nothing.
  • A task cancelled right after STARTTASK still runs up to its first yield.
  • A TRY in the task around a yield catches the cancellation (BASIC task cancelled), and the task goes on to its next yield. Add RETHROW in that CATCH.
  • Allowed inside a FUNCTION.

Example

steps = 0walker AS TASKHANDLESTARTTASK walker, WalkWait(0.1)CANCELTASK walkerAWAITTASK walkerIF TaskCancelled(walker) THEN Console("walker cancelled")   ' walker cancelledIF steps < 1000 THEN Console("stopped early")   ' stopped earlyENDWalk:  FOR i = 1 TO 1000    steps = steps + 1    YieldTask()  NEXTRETURN steps
In the manual : The game loop and tasks