2013-03-21 162 views
5

我在這裏看到類似的問題,但找不到答案。我有一個應用程序,使用WCF打開連接到遠程地址,有時當我從任務管理器中關閉應用程序或應用程序關閉時,連接保持打開,然後當我重新啓動我的應用程序時,我收到一個異常,告訴我已經存在這個端口上的一個監聽者。WCF tcp連接在進程死亡時保持打開狀態

幾個問題:

  1. 爲什麼這樣的連接保持打開後,我殺死進程?
  2. 當進程非正常關閉時,如何關閉此連接?
  3. 在嘗試創建新連接之前,如何關閉連接?

塞雷爾語方:

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; 
+0

你能否提供一些服務器端代碼 – Alex 2013-03-21 09:06:31

+0

添加一些代碼 – meirrav 2013-03-21 09:14:12

回答

0

你可以嘗試添加Channel_Closed事件處理程序,並使用中止()方法來強制處置。

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

會嘗試一下,你知道爲什麼連接保持打開? – meirrav 2013-03-21 09:47:59

+0

@meirrav是自助主機的Windows服務嗎? – Alex 2013-03-21 09:53:43

+0

它是自我主機 – meirrav 2013-03-21 09:55:52