gpt4 book ai didi

c# - 正确避免 ObjectDisposedException

转载 作者:太空宇宙 更新时间:2023-11-03 10:34:36 32 4
gpt4 key购买 nike

我遇到了一个问题,其中大约有 50% 的时间抛出了 ObjectDisposedExceptiontry 中的代码(在 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# - 正确避免 ObjectDisposedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28337760/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com