我遇到了一个问题,大约 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/