我遇到了一个问题,其中ObjectDisposedException
大约有50%的时间被抛出。下方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的原始方法似乎是唯一可以接受的答案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句