MCPcopy Create free account
hub / github.com/GoSimplicity/LinkMe / WithAsyncCancel

Function WithAsyncCancel

pkg/general/general.go:7–36  ·  view source on GitHub ↗
(ctx context.Context, cancel context.CancelFunc, fn func() error)

Source from the content-addressed store, hash-verified

5)
6
7func WithAsyncCancel(ctx context.Context, cancel context.CancelFunc, fn func() error) func() {
8 return func() {
9 go func() {
10 // 监听 context 取消信号
11 done := make(chan struct{})
12 defer close(done)
13
14 go func() {
15 select {
16 case <-ctx.Done():
17 cancel()
18 case <-done:
19 return
20 }
21 }()
22
23 // 确保 goroutine 中的 panic 不会导致程序崩溃
24 defer func() {
25 if r := recover(); r != nil {
26 cancel() // 发生 panic 时取消操作
27 }
28 }()
29
30 // 执行目标函数
31 if err := fn(); err != nil {
32 cancel() // 发生错误时取消操作
33 }
34 }()
35 }
36}

Callers 3

CreateCommentMethod · 0.92
PublishMethod · 0.92
GetPublishPostByIdMethod · 0.92

Calls

no outgoing calls

Tested by

no test coverage detected