WCF tcp connections stay open when process is kill

2019-06-22 06:54发布

问题:

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;

回答1:

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();           
        }
    }


标签: c# wcf tcp