I have a worker that has to do a lot of work to create a value. Once the value is created it sends that value using a channel.
The problem is that the work takes such a long time that sometimes the receiver on the channel will decide that it doesn’t need the value and will hang up. When that happens the worker is wasting CPU because it keeps working and doesn’t discover that the channel is closed until it tries tries to send the fully computed value.
I would like some way for the worker to periodically check to see if the channel is still valid. If it’s not, then the worker can just quit without sending any value. But as far as I can see the only way to see if a channel is valid, is by sending. Is there some other way? Or a standard design to work around the problem?
Best that I can think of is that I send an enum through the channel with two values:
Then my worker could periodically send the “AreYouStillAlive” value to see if it should continue work. And send “FinalValue” when done… but this is pretty messy because it means the receiver needs to filter and ignore all the AreYouStillAlive values. Must be better way?