当进程被终止时,WCF tcp连接保持打开状态

mei*_*rav 5 c# wcf tcp

我在这里看到过类似的问题,但找不到答案.我有一个使用WCF打开到远程地址的连接的应用程序,有时当我从任务管理器中杀死应用程序或应用程序非正常地关闭连接保持打开然后当我重新启动我的应用程序时我得到一个异常告诉我已经有这个端口上的监听器.

几个问题:

  1. 为什么这样的连接在我杀死进程后保持打开状态?
  2. 当进程非正常关闭时,如何关闭此连接?
  3. 在尝试创建新连接之前,如何关闭连接?

serer方:

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;
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 0

您可以尝试添加 Channel_Closed 事件处理程序并使用 Abort() 方法强制其处置。

    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();           
        }
    }
Run Code Online (Sandbox Code Playgroud)