CA2000 and disposal of WCF client
- by Mayo
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:
http://www.theroks.com/2011/03/04/wcf-dispose-problem-with-using-statement/
http://www.codeproject.com/Articles/151755/Correct-WCF-Client-Proxy-Closing.aspx
http://codeguru.earthweb.com/csharp/.net/net_general/tipstricks/article.php/c15941/