title: CA2000 and disposal of WCF client
body: <p>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).</p>
  
  <p>I've done my best to implement something that adheres to the numerous suggestions out there.</p>
  
  <pre><code>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 
        &amp;&amp; proxy.State != CommunicationState.Faulted)
      {
        proxy.Close();
      }
      else
      {
        proxy.Abort();
      }
    }
    catch (CommunicationException)
    {
      proxy.Abort();
    }
    catch (TimeoutException)
    {
      proxy.Abort();
    }
    catch
    {
      proxy.Abort();
      throw;
    }
  }
  </code></pre>
  
  <p>This appears to be working as intended.  However, when I run Code Analysis in Visual Studio 2010 I still get a CA2000 warning.</p>
  
  <blockquote>
    <p>CA2000 : Microsoft.Reliability : In
    method 'DoSomething()', call
    System.IDisposable.Dispose on object
    'client' before all references to it
    are out of scope.</p>
  </blockquote>
  
  <p>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?</p>
  
  <p>Related resources that I've found:</p>
  
  <ul>
  <li><a href="http://www.theroks.com/2011/03/04/wcf-dispose-problem-with-using-statement/" rel="nofollow">http://www.theroks.com/2011/03/04/wcf-dispose-problem-with-using-statement/</a></li>
  <li><a href="http://www.codeproject.com/Articles/151755/Correct-WCF-Client-Proxy-Closing.aspx" rel="nofollow">http://www.codeproject.com/Articles/151755/Correct-WCF-Client-Proxy-Closing.aspx</a></li>
  <li><a href="http://codeguru.earthweb.com/csharp/.net/net_general/tipstricks/article.php/c15941/" rel="nofollow">http://codeguru.earthweb.com/csharp/.net/net_general/tipstricks/article.php/c15941/</a></li>
  </ul>