5

I've seen similar questions here but couldn't find an answer. i have an app that uses WCF to open a connection to remote address, sometimes when i kill the app from the task manager or the app closes ungracefully the connection stays open and then when i restart my app i get an exception telling me there is already a listener on this port.

few questions :

  1. why such connections stay open after i kill the process?
  2. how can i close this connections when the process closes ungracefully?
  3. how can i close the connections before i try to create a new one?

serer side :

var url = Config.GetRemoteServerUrl();
var binding = new NetTcpBinding();

binding.Security.Mode = SecurityMode.None;
binding.ReliableSession.Enabled = Config.RelaiableSession;
binding.ReliableSession.InactivityTimeout = TimeSpan.MaxValue;
binding.MaxConnections = Config.MaxConcurrentSessions;
binding.ReaderQuotas.MaxArrayLength = Config.ReaderQuotasMaxArrayLength;
binding.MaxReceivedMessageSize = Config.MaxReceivedMessageSize;
binding.SendTimeout = new TimeSpan(0,0, 0, 0,Config.SendTimeout);
binding.OpenTimeout = new TimeSpan(0,0, 0, 0,Config.OpenTimeout);

host = new ServiceHost(ServerFacade.Instance, new Uri[] { new Uri(url) });

host.AddServiceEndpoint(typeof(ITSOServiceContract), binding, url);

host.Open();

serverFacade = host.SingletonInstance as IServerFacade;
J. Steen
  • 15,470
  • 15
  • 56
  • 63
meirrav
  • 761
  • 1
  • 9
  • 27

1 Answers1

0

You can try to add Channel_Closed event handler and use Abort() method to force it to dispose.

    OperationContext.Current.Channel.Closed += channelClosed;


    void Channel_Closed(object sender, EventArgs e)
    {
        var success = false;
        try
        {           
           proxy.Close();
           success = true;
        }
        finally
        {
          if (!success) proxy.Abort();           
        }
    }
Alex
  • 8,827
  • 3
  • 42
  • 58
  • ll try it, do you know why the connection stays open? – meirrav Mar 21 '13 at 09:47
  • @meirrav is it windows service of self-host? – Alex Mar 21 '13 at 09:53
  • @meirrav Well, I suppose it could be the specific of TCP Socket model. In msdn it is said that: "Based on the LingerState property, the TCP connection may stay open for some time after the Close method is called when data remains to be sent. There is no notification provided when the underlying connection has completed closing." http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.close.aspx So I suppose the NetTcpBinding follows the same behaviour – Alex Mar 21 '13 at 10:03