CA2000 and disposal of WCF client
Posted
by
Mayo
on Stack Overflow
See other posts from Stack Overflow
or by Mayo
Published on 2011-03-09T16:07:24Z
Indexed on
2011/03/09
16:10 UTC
Read the original article
Hit count: 1158
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:
© Stack Overflow or respective owner