c# - 正确避免 ObjectDisposeException

标签 c# exception objectdisposedexception

我遇到了一个问题,大约 50% 的情况下会抛出 ObjectDisposeException。下面 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.
            }
        }
    }

最佳答案

怎么样

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 的原始方法似乎是唯一可接受的答案。

关于c# - 正确避免 ObjectDisposeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28337760/

相关文章:

c# - 长字符串的多子字符串

c# - Unity3d Swipe 跳转不是很灵敏

c# - 如何在C#/MVVM应用程序中解决无法解释的ObjectDisposedExceptions?

c# - ObjectDisposedException - DangerousAddRef

c# - 如何创建模块化 Blazor Web 应用

c# - 清除 Crystal Reports ReportDocument 对象使用的资源的最佳方法是什么?

multithreading - 单元测试时如何处理其他线程中引发的异常?

java - 为什么0代表java.lang.Class.forName0?

c# - 异常的 "message"是否具有文化独立性?

c# - 检查 IsDisposed 和 Disposing 时为 "Cannot access a disposed object"