I need to invoke a function that takes a Context
as a parameter. This block of code has access to a channel that is used for signalling that the operation should be cancelled.
Here is what I am currently using to cancel the Context
when a value is received:
func doSomething(stop <-chan bool) {
ctx, cancel := context.WithCancel(context.Background())
go func() {
select {
case <-ctx.Done():
case <-stop:
cancel()
}
}()
longRunningFunction(ctx)
}
The intended control flow is as follows:
If the task runs to completion, it will cancel the context, the
<-ctx.Done()
will fire, and the goroutine will terminate.If a value is received on
stop
, the context is cancelled, notifying the task that it should quit. Once again, the goroutine will terminate when this happens.
This seems overly complex. Is there a simpler way to accomplish the intended behavior?