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

时间:2013-03-21 09:04:26

标签: c# wcf tcp

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

几个问题:

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

1 个答案:

答案 0 :(得分: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();           
        }
    }