Go context.Canceled
A cancelled context lets cooperating work distinguish a cancellation request from a deadline.
A simple example
context.Canceled
- Start with A pending task is cancelled
- Do this Ask for its result
- Result Cancellation reported
Syntax
errors.Is(ctx.Err(), context.Canceled)
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goCollect a cancelled print job
A student cancels a print job before the printer starts. When the dashboard later requests the result, it should show the cancellation as a distinct outcome.
package main
import (
"context"
"errors"
"fmt"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
<-ctx.Done()
if errors.Is(ctx.Err(), context.Canceled) {
fmt.Println("Print job cancelled")
}
}
Print job cancelled
The cancellation is visible before any result is collected. The dashboard can label the job accordingly.
Collect a finished poster
The print room records completion before the clerk calls for the result. Collect the result of the print job. A cancelled job should be removed from the collection queue.
Collect a withdrawn badge job
A class withdraws its badge job before printing begins. Collect the result of the print job. A cancelled job should be removed from the collection queue.
What to watch for
A context communicates a request. The worker must choose where to stop.