Junior — Middle
What is the role of the Context.Done method in managing the completion of asynchronous operations?
sobes.tech AI
Answer from AI
The Context.Done() method returns a channel that is closed when the context is canceled or its deadline expires. This allows asynchronous operations to monitor the completion signal and terminate properly.
For example, in a goroutine, you can listen to this channel and end the work when the context is canceled:
ctx, cancel := context.WithCancel(context.Background())
go func() {
select {
case <-ctx.Done():
// Context canceled, end work
return
case data := <-dataCh:
// Process data
}
}()
// Later, call cancel() to stop the goroutine
cancel()
Thus, Context.Done() serves as a signal for safe and timely termination of asynchronous operations.