snippetgoTippending
Go context.AfterFunc for cleanup on cancellation
Viewed 0 times
Go 1.21+
contextAfterFunccancellationcleanupcallback
Problem
Running cleanup code when a context is cancelled requires spawning a goroutine to watch ctx.Done().
Solution
Use context.AfterFunc (Go 1.21+) for cleaner cancellation callbacks:
ctx, cancel := context.WithCancel(context.Background())
// Register cleanup
stop := context.AfterFunc(ctx, func() {
log.Println("context cancelled, cleaning up...")
conn.Close()
})
// If you want to prevent the func from running:
if stopped := stop(); stopped {
// func was prevented from running
}
// When cancel() is called, the func runs in a new goroutine
cancel()
ctx, cancel := context.WithCancel(context.Background())
// Register cleanup
stop := context.AfterFunc(ctx, func() {
log.Println("context cancelled, cleaning up...")
conn.Close()
})
// If you want to prevent the func from running:
if stopped := stop(); stopped {
// func was prevented from running
}
// When cancel() is called, the func runs in a new goroutine
cancel()
Why
AfterFunc simplifies the common pattern of watching for context cancellation without manually managing goroutines.
Revisions (0)
No revisions yet.