正确避免ObjectDisposedException

时间:2015-02-05 06:46:19

标签: c# exception objectdisposedexception

我遇到了一个大约50%的时间被抛出ObjectDisposedException的问题。 try(位于finally)内的代码导致异常。我不知道如何处理这件事。我可以吃掉异常,如下所示,但有没有办法检查和关闭对象而不会发生异常?

    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.
            }
        }
    }

3 个答案:

答案 0 :(得分:2)

怎么样

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);
    }
}

<强>更新

似乎DiscoveryClient.Dispose()会抛出异常。 OP的原创方法似乎是唯一可以接受的答案。

答案 1 :(得分:1)

虽然我不太确定你为什么遇到它,但你可以尝试以下普通的WCF客户端:

如果您在discoveryClient上有“State”属性,请尝试以下防御性检查:

finally
        {
            try
            {
                if (discoveryClient != null) 
                { 
                  if(discoveryClient.State == CommunicationState.Faulted)
                  {
                     discoveryClient.Abort();
                  }
                  else if(discoveryClient.State != CommunicationState.Closed )
                  {
                     discoveryClient.Close();
                  }
            }
            catch (ObjectDisposedException)
            {

            }
        }

希望这对你有所帮助。

答案 2 :(得分:-1)

另外,我建议对IDisposable对象使用“using”。考虑DiscoveryClient是IDisposable,

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

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

            using (DiscoveryClient discoveryClient = new DiscoveryClient(discoveryEndpoint))
            {
                response = discoveryClient.Find(findCriteria);
                discoveryClient.Close();
            }
        }
        finally
        {   
            // other finalizing works, like clearing lists, dictionaries etc.
        }
        return response;
    }