Use `ctx.Done()` instead of `time.NewTimer()` as a replacement of `time.After()`?
RussellLuo opened this issue · comments
Luo Peng commented
Hi there!
Regarding this suggestion:
time.After() leaks until it fires; use t := NewTimer(); t.Stop() / t.Reset()
AFAIK, I'm afraid time.NewTimer()
is also difficult to use correctly.
How about using ctx.Done()
as a replacement of time.After()
?
For example, instead of doing this:
select {
case value := <-C:
// handle value
case <-time.After(5 * time.Second):
// timeout elapses
}
Maybe we should do this:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
select {
case value := <-C:
// handle value
case <-ctx.Done():
// timeout elapses
}