3 ms·
It does not need to be the background. You can check context cancellation without any goroutines by: select { default: case <-ctx.Done(): r
by fishywang 7y ago
It does not need to be the background. You can check context cancellation without any goroutines by:
select {
default:
case <-ctx.Done():
return ctx.Err()
}
When there's no other channels to select with the context, just use that code block between lengthy operations to check context cancellation and return early.
(If you are curious about how many extra time is wasted, it's easy to write a benchmark test for that. Last time I checked it was ~20ns when you are going the default/not-cancelled route)
- _caw 7y agoYou may also simply write the following, which appears more elegant than the select. if ctx.Err() != nil { //then the context has expired or been cancelled }