有大量有关 WCF 客户端的信息,并且您不能简单地依赖 using 语句来处理客户端。这是因为 Close 方法可能会引发异常(即,如果托管服务的服务器没有响应)。
我已尽力实施符合众多建议的措施。
public void DoSomething()
{
MyServiceClient client = new MyServiceClient(); // from service reference
try
{
client.DoSomething();
}
finally
{
client.CloseProxy();
}
}
public static void CloseProxy(this ICommunicationObject proxy)
{
if (proxy == null)
return;
try
{
if (proxy.State != CommunicationState.Closed
&& proxy.State != CommunicationState.Faulted)
{
proxy.Close();
}
else
{
proxy.Abort();
}
}
catch (CommunicationException)
{
proxy.Abort();
}
catch (TimeoutException)
{
proxy.Abort();
}
catch
{
proxy.Abort();
throw;
}
}
这似乎按预期工作。但是,当我在 Visual Studio 2010 中运行代码分析时,我仍然收到 CA2000 警告。
CA2000:Microsoft.Reliability:在
方法“DoSomething()”,调用
对象上的 System.IDisposable.Dispose
'client' 在所有引用之前
超出范围。
我可以对我的代码做些什么来消除警告,或者一旦我确信我正在尽一切可能确保客户端被处理掉,我应该使用 SuppressMessage 来隐藏此警告吗?
我找到的相关资源:
There is plenty of information out there concerning WCF clients and the fact that you cannot simply rely on a using statement to dispose of the client. This is because the Close method can throw an exception (i.e. if the server hosting the service doesn't respond).
I've done my best to implement something that adheres to the numerous suggestions out there.
public void DoSomething()
{
MyServiceClient client = new MyServiceClient(); // from service reference
try
{
client.DoSomething();
}
finally
{
client.CloseProxy();
}
}
public static void CloseProxy(this ICommunicationObject proxy)
{
if (proxy == null)
return;
try
{
if (proxy.State != CommunicationState.Closed
&& proxy.State != CommunicationState.Faulted)
{
proxy.Close();
}
else
{
proxy.Abort();
}
}
catch (CommunicationException)
{
proxy.Abort();
}
catch (TimeoutException)
{
proxy.Abort();
}
catch
{
proxy.Abort();
throw;
}
}
This appears to be working as intended. However, when I run Code Analysis in Visual Studio 2010 I still get a CA2000 warning.
CA2000 : Microsoft.Reliability : In
method 'DoSomething()', call
System.IDisposable.Dispose on object
'client' before all references to it
are out of scope.
Is there something I can do to my code to get rid of the warning or should I use SuppressMessage to hide this warning once I am comfortable that I am doing everything possible to be sure the client is disposed of?
Related resources that I've found:
发布评论
评论(1)
您可以在调用
CloseProxy
之后,在finally
块中添加对Dispose
的调用。那时,您可以合理地确定Dispose
不会抛出异常,尽管添加多余的代码只是来保持代码分析愉快似乎有点愚蠢 - 我可能会只是压制该消息。(无论您选择哪个选项,都请包含非常清晰的注释,解释代码执行此操作的原因。)
You could add a call to
Dispose
in yourfinally
block, after the call toCloseProxy
. At that point you can be reasonably sure thatDispose
won't throw, although it seems a bit silly to add superfluous code just to keep code analysis happy - I'd probably just suppress the message.(Whichever option you choose, include very clear comments explaining why the code does what it does.)