title: C# Wcf connections causing TCP/IP Port Exhaustion
body: <p>I'm working on an ASP.NET MVC project and found several connections to a WCF service that are not closed and I think this is causing a TCP/IP Port Exhaustion.</p>
  
  <p>I checked the server at the Resource Monitor/Network/TCP Connections and there are thousands of gray connections as "IPV6 Loopback" and at some point there are so many connections that the server stops responding on the service port.</p>
  
  <p>Existis a dependency injection to work with the connections on the controllers and there is a "CloseChannel" method, but it was not called, I made some changes to it and started calling it in the Dipose method on the controllers to close the connections, but I did not get any results. The loopbacks continue to appear.</p>
  
  <p>Two solutions I think to do is:</p>
  
  <ul>
  <li><p>Remove the dependency injection and create the connection normaly
  on each time with using.</p>
  
  <p>Beside closing connections make some changes on the server as
  described in this <a href="https://social.technet.microsoft.com/Forums/windowsserver/en-US/88e32b0b-985b-41dd-ac0d-19ce47211c91/is-this-a-kind-of-tcpip-port-exhaustion-whenever-we-had-this-issue-we-are-rebooting-server?forum=winserverNIS" rel="nofollow noreferrer">post</a></p></li>
  </ul>
  
  <p>Doubt:
  Is there any better option than the ones I proposed? If not, which one is the best in your opinion?</p>
  
  <p>Thank you all!</p>
  
  <p>PS.: Code used today to open and close connections:</p>
  
  <p><strong>This is called onthe controller:</strong></p>
  
  <pre><code>IClient wcfClient = WcfChannel.CreateChannel&lt;IClient&gt;(connectionstr, WcfChannel.WcfBinding.NetTcpBinding);
  </code></pre>
  
  <p><strong>This is the WcfChannel:</strong></p>
  
  <pre><code>public static class WcfChannel
  {
      public static T CreateChannel&lt;T&gt;(string endpointAddress, WcfBinding wcfBinding)
      {
          Binding binding = null;
  
          #region ReaderQuotas
          XmlDictionaryReaderQuotas readerQuotas = new XmlDictionaryReaderQuotas()
          {
              MaxDepth = int.MaxValue,
              MaxStringContentLength = int.MaxValue,
              MaxArrayLength = int.MaxValue,
              MaxBytesPerRead = int.MaxValue,
              MaxNameTableCharCount = int.MaxValue
          };
          #endregion
  
          switch (wcfBinding)
          {
              case WcfBinding.BasicHttpBinding:
              case WcfBinding.NetMsmqBinding:
              case WcfBinding.NetNamedPipeBinding:
                  throw new NotImplementedException();
  
              case WcfBinding.NetTcpBinding:
                  binding = new NetTcpBinding()
                  {
                      Name = "NetTcpBinding",
                      MaxBufferPoolSize = long.MaxValue,
                      MaxBufferSize = int.MaxValue,
                      MaxReceivedMessageSize = int.MaxValue,
                      ReaderQuotas = readerQuotas,
                      Security = new NetTcpSecurity() { Mode = SecurityMode.None },
                      CloseTimeout = new TimeSpan(0, 5, 0),
                      OpenTimeout = new TimeSpan(0, 5, 0),
                      ReceiveTimeout = new TimeSpan(0, 5, 0),
                      SendTimeout = new TimeSpan(0, 5, 0)
                  };
                  break;
  
              case WcfBinding.NetTcpBindingStreamed:
                  binding = new NetTcpBinding()
                  {
                      Name = "NetTcpBindingStreamed",
                      TransferMode = TransferMode.Streamed,
                      MaxBufferPoolSize = long.MaxValue,
                      MaxBufferSize = int.MaxValue,
                      MaxReceivedMessageSize = int.MaxValue,
                      ReaderQuotas = readerQuotas,
                      Security = new NetTcpSecurity() { Mode = SecurityMode.None },
                      CloseTimeout = new TimeSpan(0, 5, 0),
                      OpenTimeout = new TimeSpan(0, 5, 0),
                      ReceiveTimeout = new TimeSpan(0, 5, 0),
                      SendTimeout = new TimeSpan(0, 5, 0)
                  };
                  break;
              case WcfBinding.WS2007HttpBinding:
              case WcfBinding.WSHttpBinding:
                  throw new NotImplementedException();
              default:
                  throw new NotImplementedException();
          }
  
          EndpointAddress endpoint = new EndpointAddress(endpointAddress);
  
          var channelFactory = new ChannelFactory&lt;T&gt;(binding, endpoint);
          T channelObj = channelFactory.CreateChannel();
  
          return channelObj;
      }
  
      public static void CloseChannel(this object obj)
      {
          if (obj != null)
          {
              try
              {
                  (obj as IClientChannel).Close();
              }
              catch (CommunicationException)
              {
                  if (obj.GetType().GetMethod("Abort") != null)
                  {
                      (obj as IClientChannel).Abort();
                  }
              }
              catch (TimeoutException)
              {
                  if (obj.GetType().GetMethod("Abort") != null)
                  {
                      (obj as IClientChannel).Abort();
                  }
              }
              catch (Exception)
              {
                  //many connections doesn't have and Abort or close
              }
  
  
              if (obj.GetType().GetMethod("Dispose") != null)
              {
                  (obj as IDisposable).Dispose();
              }
  
              obj = null;
          }
      }
  
      public enum WcfBinding
      {
          BasicHttpBinding,
          NetMsmqBinding,
          NetNamedPipeBinding,
          NetTcpBinding,
          NetTcpBindingStreamed,
          WS2007HttpBinding,
          WSHttpBinding
      }
  }
  </code></pre>