Search code examples
c#.netudpclientobjectdisposedexception

Catching an ObjectDisposedException thrown at UDPClient.EndReceive


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?


Solution

  • I ended up using a bool flag to indicate that the service was stopping. The serviceStopping flag is set to true in the OnStop() method of the service, and checked when the ObjectDisposedException is caught:

    try 
    {
        datagram = client.EndReceive(arClient, ref remoteEP); 
    }
    catch (ObjectDisposedException)
    {
        //if the service is stopping this is expected
        if(serviceStopping)
        {
            //return without further processing
            //in the receiveCallback
            return;
        }
    
        //otherwise rethrow the exception
        throw;
    }