Unregister Cleanup With context.AfterFunc Stop

Attach a cancel hook with context.AfterFunc to close an in-flight resource, and unregister the hook via defer stop() when work finishes early.

GoResilience

Code

snippet
package main

import (
	"context"
	"errors"
	"fmt"
	"sync"
)

type Resource struct {
	name   string
	mu     sync.Mutex
	closed bool
}

func (r *Resource) CloseWithReason(reason string) bool {
	r.mu.Lock()
	defer r.mu.Unlock()
	if r.closed {
		return false
	}
	r.closed = true
	fmt.Printf("[%s] closed by %s\n", r.name, reason)
	return true
}

func runTask(ctx context.Context, res *Resource, finishEarly bool) error {
	stopped := make(chan struct{})
	stop := context.AfterFunc(ctx, func() {
		defer close(stopped)
		res.CloseWithReason("AfterFunc:" + context.Cause(ctx).Error())
	})
	defer func() {
		if !stop() {
			<-stopped
		}
	}()
	if finishEarly {
		res.CloseWithReason("normal-completion")
		return nil
	}
	<-ctx.Done()
	return context.Cause(ctx)
}

func main() {
	r1 := &Resource{name: "conn-1"}
	ctx1, cancel1 := context.WithCancelCause(context.Background())
	fmt.Println("early path err:", runTask(ctx1, r1, true))
	cancel1(errors.New("late-cancel"))

	r2 := &Resource{name: "conn-2"}
	ctx2, cancel2 := context.WithCancelCause(context.Background())
	go func() { cancel2(errors.New("deadline-hit")) }()
	fmt.Println("canceled path err:", runTask(ctx2, r2, false))
}

Execution path — Unregister Cleanup With context.AfterFunc Stop

The snippet is organized around the functions CloseWithReason, runTask and main.

Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. Cleanup is attached with defer, so it runs on every exit path of the function.

Watch out for

  • Zero packages pulled in — the runtime ships every API this code touches.

Putting it to use

Entry signature: func (r *Resource) CloseWithReason(reason string) bool

The file’s steps show up in the output as early path err:, canceled path err:.

main sequences runTask; executing the file runs that flow once.

Core lines

go func() { cancel2(errors.New("deadline-hit")) }()
return context.Cause(ctx)
func (r *Resource) CloseWithReason(reason string) bool {
	r.mu.Lock()
	defer r.mu.Unlock()
	if r.closed {
		return false
	}
	r.closed = true
	fmt.Printf("[%s] closed by %s\n", r.name, reason)
	return true
}

Interactive Tools for This Topic

FAQ

What does Unregister Cleanup With context.AfterFunc Stop print when run?
Running the file directly is enough — expect labeled output lines such as `early path err:`, `canceled path err:`.