title: How to properly close a client proxy (An existing connection was forcibly closed by the remote host)?
body: <p>Please don't close as duplicate until you read the question to the end; I already googled for hours without success.</p>
  <hr />
  <p>EDIT: Now I'm convinced it's related to the way WCF caches opened TCP connections (connection pooling). Please take a look at edit #5 at the end of he question.</p>
  <hr />
  <p>I basically have a WCF service that uses a <code>netTcpBinding</code> configuration. Even if I close the client proxy gracefully (see code below), server always logs  &quot;<code>System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host</code>&quot;.</p>
  <p>I've narrowed down the issue to the most basic WCF example I could write. I'm getting the exception in the logs produced by WCF tracing <strong>every-time I close the client application</strong>. I'm not getting any exception in my own code though, which means it works as expected and I can't debug anything to see what's going wrong for WCF to add an error in my logs.</p>
  <p>Service interface/implementation:</p>
  <pre><code>[ServiceContract]
  public interface IService1
  {
      [OperationContract]
      string DoWork();
  }
  ...
  public class Service1 : IService1
  {
      public string DoWork()
      {
          return &quot;12&quot;;
      }
  }
  </code></pre>
  <p>Server-side configuration:</p>
  <pre><code>&lt;configuration&gt;
    &lt;system.web&gt;
      &lt;compilation debug=&quot;true&quot; targetFramework=&quot;4.5&quot; /&gt;
      &lt;httpRuntime targetFramework=&quot;4.5&quot; /&gt;
    &lt;/system.web&gt;
    &lt;system.serviceModel&gt;
      &lt;behaviors&gt;
        &lt;serviceBehaviors&gt;
          &lt;behavior name=&quot;&quot;&gt;
            &lt;serviceMetadata httpGetEnabled=&quot;true&quot; httpsGetEnabled=&quot;true&quot; /&gt;
            &lt;serviceDebug includeExceptionDetailInFaults=&quot;true&quot; /&gt;
          &lt;/behavior&gt;
        &lt;/serviceBehaviors&gt;
      &lt;/behaviors&gt;
      &lt;serviceHostingEnvironment aspNetCompatibilityEnabled=&quot;true&quot; multipleSiteBindingsEnabled=&quot;true&quot; /&gt;
      &lt;services&gt;
        &lt;service name=&quot;WebApplication1.Service1&quot;&gt;
          &lt;endpoint address=&quot;&quot; binding=&quot;netTcpBinding&quot; bindingConfiguration=&quot;netTcpEndpointBinding&quot; contract=&quot;WebApplication1.IService1&quot; /&gt;
        &lt;/service&gt;
      &lt;/services&gt;
      &lt;bindings&gt;
        &lt;netTcpBinding&gt;
          &lt;binding name=&quot;netTcpEndpointBinding&quot;&gt;
            &lt;security mode=&quot;None&quot; /&gt;
          &lt;/binding&gt;
        &lt;/netTcpBinding&gt;
      &lt;/bindings&gt;
    &lt;/system.serviceModel&gt;
  &lt;/configuration&gt;
  </code></pre>
  <p>Client-side configuration:</p>
  <pre><code>&lt;configuration&gt;
    &lt;system.serviceModel&gt;
      &lt;bindings&gt;
        &lt;netTcpBinding&gt;
          &lt;binding name=&quot;NetTcpBinding_IService1&quot;&gt;
            &lt;security mode=&quot;None&quot; /&gt;
          &lt;/binding&gt;
        &lt;/netTcpBinding&gt;
      &lt;/bindings&gt;
      &lt;client&gt;
        &lt;endpoint address=&quot;net.tcp://localhost/WebApplication1/Service1.svc&quot;
          binding=&quot;netTcpBinding&quot; bindingConfiguration=&quot;NetTcpBinding_IService1&quot;
          contract=&quot;ServiceReference1.IService1&quot; name=&quot;NetTcpBinding_IService1&quot; /&gt;
      &lt;/client&gt;
    &lt;/system.serviceModel&gt;
  &lt;/configuration&gt;
  </code></pre>
  <p>Client-side code that consumes the service (VS2012 generated the client proxy for me using &quot;Add service reference&quot;):</p>
  <pre><code>private async Task&lt;string&gt; TestTask()
  {
      Service1Client proxy = null;
  
      try
      {
          Console.WriteLine(&quot;Calling service&quot;);
  
          proxy = new Service1Client();
          return await proxy.DoWorkAsync();
      }
      finally
      {
          if (proxy.State != System.ServiceModel.CommunicationState.Faulted)
          {
              Console.WriteLine(&quot;Closing client&quot;);
              proxy.Close();
          }
          else
          {
              Console.WriteLine(&quot;Aborting client&quot;);
              proxy.Abort();
          }
      }
  }
  </code></pre>
  <p>Everything works fine:</p>
  <blockquote>
  <p>Calling service</p>
  <p>Closing client</p>
  <p>12</p>
  </blockquote>
  <p>But as soon as the application terminates, the server logs an exception. I understand I shouldn't be worried about this exception because it works as expected (exception only appears in logs) and could happen anyway in case the client is terminated abruptly before calling <code>.Close()</code>/<code>.Abort()</code>.</p>
  <p>But still, is this a normal behavior? I mean, if I correctly closes my client proxy, I expect the server to <strong>not</strong> log an exception (that is polluting my logs).
  I also assume some TCP connection is still established between the client and the server (unknown state) after closing the client proxy, because the server only logs the exception after the whole client application terminates. If such a connection is still opened, can't this introduce unexpected behavior (such as max number of connected clients)? Is this really expected?</p>
  <p>I found different threads about the issue:</p>
  <p><a href="http://social.msdn.microsoft.com/Forums/vstudio/en-US/0f548f9b-7051-46eb-a515-9185f504d605/error-using-nettcpbinding-an-existing-connection-was-forcibly-closed-by-the-remote-host?forum=wcf" rel="noreferrer">http://social.msdn.microsoft.com/Forums/vstudio/en-US/0f548f9b-7051-46eb-a515-9185f504d605/error-using-nettcpbinding-an-existing-connection-was-forcibly-closed-by-the-remote-host?forum=wcf</a></p>
  <p><a href="https://stackoverflow.com/questions/13761108/wcf-an-existing-connection-was-forcibly-closed-by-the-remote-host-after-closin">wcf &quot;An existing connection was forcibly closed by the remote host&quot; after closing client</a></p>
  <p>The conclusion would be &quot;don't care about it&quot;.</p>
  <p>Could someone confirm that with some references and explain why this exception is thrown anyway?</p>
  <p>EDIT:</p>
  <p>Log trace of the exception:</p>
  <pre><code>&lt;Exception&gt;
  &lt;ExceptionType&gt;System.Net.Sockets.SocketException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&lt;/ExceptionType&gt;
  &lt;Message&gt;An existing connection was forcibly closed by the remote host&lt;/Message&gt;
  &lt;StackTrace&gt;
  à System.ServiceModel.Channels.SocketConnection.HandleReceiveAsyncCompleted()
  à System.ServiceModel.Channels.SocketConnection.OnReceiveAsync(Object sender, SocketAsyncEventArgs eventArgs)
  à System.Net.Sockets.SocketAsyncEventArgs.FinishOperationAsyncFailure(SocketError socketError, Int32 bytesTransferred, SocketFlags flags)
  à System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
  à System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
  &lt;/StackTrace&gt;
  &lt;ExceptionString&gt;System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host&lt;/ExceptionString&gt;
  &lt;NativeErrorCode&gt;2746&lt;/NativeErrorCode&gt;
  &lt;/Exception&gt;
  </code></pre>
  <p>Thanks a lot</p>
  <p>EDIT 2: I have the same problem when hosting the service in IIS or when it's self-hosted in a Windows service</p>
  <p>EDIT 3: <strong>here's a full example to reproduce the issue</strong>: <a href="http://speedy.sh/ENB59/wcf-test.zip" rel="noreferrer">http://speedy.sh/ENB59/wcf-test.zip</a></p>
  <p>EDIT 4:</p>
  <p>I tried to monitor what is actually happening under the hood with the TCP connection WCF establishes for me.</p>
  <p>After closing the client proxy, I still see an opened TCP connection to my server:</p>
  <p><img src="https://i.stack.imgur.com/XSqee.png" alt="enter image description here" /></p>
  <p>I assume this is related to the TCP connection to be cached for a future re-use (i.e. connection pooling), because opening a new connection to the server (after the first client proxy has been closed) doesn't create a new TCP connection. If I call <code>Console.WriteLine(new Test().TestTask().Result);</code> twice in my application, I still only see one opened TCP connection.</p>
  <p>I also noted this connection dies because of a timeout if I wait too long after closing the client channel.</p>
  <p>EDIT 5: OK, I found documentation on MSDN about that connection pooling:</p>
  <blockquote>
  <p>The NetTcpBinding uses TCP connection pooling based on the service’s
  host DNS name and the port number the service is listening on. This
  works well when a client makes calls to different services on
  different ports, or services are hosted in a single process and share
  a port. If a single client calls multiple services sharing a port that
  are hosted in different processes, or are WAS/IIS hosted, the client
  side pooling may lead to problems where a connection to Service A is
  reused for Service B, resulting in an exception being thrown, the
  connection aborted, and a new channel created. To avoid this problem,
  use a CustomBinding and specify a different
  ConnectionPoolSettings.GroupName for each service the client
  communicates with.</p>
  </blockquote>
  <p><strong>So now my question would be: if that's a normal behavior, what could I do to prevent my log to be polluted with all those exceptions?</strong></p>