Blitz3D+ Command Reference

CancelJob job

Parameters

job - a Job handle returned by StartJob

Description

Requests cooperative cancellation of a job.

Use it when the work stops mattering - the player closed the map screen mid-pathfind, or a newer request replaced this one. The request returns immediately; it never yanks the worker mid-instruction. Still-queued work is cancelled straight away where practical, and a running worker notices at its next safe point - the compiler plants those at every Worker Function entry and loop backedge, and JobCancelled lets long indivisible steps check by hand.

Cancellation is a request, not an instant state change: a job that had already finished when the request arrived keeps its state, so the terminal state you eventually observe can be JOB_CANCELLED, JOB_SUCCEEDED, or JOB_FAILED. Keep polling until the job is terminal, then FreeJob it. Calling CancelJob repeatedly, or on a job that already finished, is harmless. If you do not care about observing the outcome at all, FreeJob alone also requests cancellation and is one call instead of two.

For the full story, see the Using Background Jobs guide.

Requires Extended mode.

See also: JobCancelled, JobState, FreeJob, PollJob, StartJob.

Example

; CancelJob Example
; -----------------
; Requires Extended mode.

Graphics 640,480,0,2
SetBuffer BackBuffer()

; The worker digs a huge cavern system - far too slow to wait for
Worker Function DigCaverns(inputBank)
    chambers=PeekInt(inputBank,0)
    For chamber=1 To chambers
        ; Busy digging loop standing in for real level generation
        For dig=1 To 500000
            noise#=Sin(dig)*Sqr(dig)
        Next
        SetJobProgress chamber,chambers,"Digging chamber "+chamber
    Next
    Return CreateBank()
End Function

inputBank=CreateBank(4)
PokeInt inputBank,0,200
job=StartJob(DigCaverns,inputBank,1L)
FreeBank inputBank

While Not KeyDown(1)

    Cls

    ; Space requests cooperative cancellation - repeating it is harmless
    If KeyHit(57) Then CancelJob job

    state=JobState(job)
    stateName$="JOB_RUNNING"
    If state=JOB_QUEUED Then stateName="JOB_QUEUED"
    If state=JOB_SUCCEEDED Then stateName="JOB_SUCCEEDED"
    If state=JOB_CANCELLED Then stateName="JOB_CANCELLED"

    ; Draw the loading bar - it freezes where the worker was stopped
    progress=JobProgress(job)
    Color 60,60,80
    Rect 70,220,500,24,True
    Color 90,200,120
    If state=JOB_CANCELLED Then Color 200,90,90
    Rect 70,220,progress*500/1000,24,True
    Color 255,255,255
    Rect 70,220,500,24,False

    Text 0,0,"Space: CancelJob   Esc: exit"
    Text 70,190,"Digging 200 cavern chambers - this would take ages"
    Text 70,254,"State: "+stateName+"   "+JobProgressText(job)
    If state=JOB_CANCELLED Then Text 70,274,"The worker stopped at its next cancellation safe point"

    Flip

Wend

FreeJob job
End

Index