Search code examples
c#exceptionobjectdisposedexception

Properly Avoid ObjectDisposedException


I ran into an issue where an ObjectDisposedException is being thrown roughly 50% of the time. The code within the try (within the finally) below, is causing the exception. I'm not sure how to handle this. I could just eat the exception, like shown below, but is there a way to check and close the object without the exception happening?

    public static FindResponse Discover(FindCriteria findCriteria, 
                                        DiscoveryEndpoint discoveryEndpoint = null)
    {
        DiscoveryClient discoveryClient = null;

        try
        {
            if (discoveryEndpoint == null) { 
                 discoveryEndpoint = new UdpDiscoveryEndpoint(); 
            }

            discoveryClient = new DiscoveryClient(discoveryEndpoint);

            return discoveryClient.Find(findCriteria);
        }
        finally
        {
            try
            {
                if (discoveryClient != null)
                {
                    discoveryClient.Close();
                }
            }
            catch (ObjectDisposedException)
            {
                // Eat it.
            }
        }
    }

Solution

  • How about

    public static FindResponse Discover(FindCriteria findCriteria, DiscoveryEndpoint discoveryEndpoint = null)
    {
        if (discoveryEndpoint == null) 
          discoveryEndpoint = new UdpDiscoveryEndpoint();
    
        using (var client = new DiscoveryClient(discoveryEndpoint))
        {
            return client.Find(findCriteria);
        }
    }
    

    Update

    Seems DiscoveryClient.Dispose() will throw exceptions. OP's original approach seems like the only acceptable answer.