I'm using an async callback in a windows service to receive UDP data broadcast on a network.
The callback uses the UDPClient.EndReceive()
method to end the pending async receive. During the service OnStop()
method I UDPClient.Close()
the UDP client. Following this, I frequently get an ObjectDisposedException
at the next call to EndReceive()
in the async callback, which is being accessed on another thread.
Obviously it's no problem for me to catch this exception in the receive callback with a try { UDPClient.EndReceive(...); }
but I would like to have some confidence that the caught ODE was thrown while shutting down the service (as expected) and not for some other reason. I could create a boolean flag that is set and indicates when the service is stopping, and check this in the catch
block, however I feel like I am overlooking a more elegant solution.
How can I ensure that the ODE I am catching is the expected one, and not a genuinely unexpected exception?