2010-10-12 79 views
6

我已經創造了IIS和WCF客戶舉辦了簡單的WCF服務,並想通了,當u趕上從WCF服務的FaultException,然後調用客戶端後,不釋放會議。中止()釋放會話(如微軟樣本所述),它不釋放會話並在第11次呼叫掛斷。中止()WCF客戶端代理的方法捕獲的FaultException

這裏是例子:

WCF服務:

[ServiceContract] 
public interface IService1 
{ 
    [OperationContract] 
    string GetData(int value); 
} 


public class Service1 : IService1 
{ 
    public string GetData(int value) 
    { 
     throw new FaultException("Exception is here"); 

     return string.Format("You entered: {0}", value); 
    } 
} 

客戶:

class Program 
{ 
    static void Main(string[] args) 
    { 
     Service1Client client = null;   

     for(int i = 0; i < 15; i++) 
     { 
      try 
      { 
       client = new Service1Client(); 
       client.GetData(100);     
      } 
      catch (TimeoutException timeoutEx) 
      { 
       Console.WriteLine(timeoutEx); 
       client.Abort(); 
      } 
      catch (FaultException faultEx) 
      { 
       Console.WriteLine(faultEx); 
       client.Abort(); 
      } 
      catch (CommunicationException commEx) 
      { 
       Console.WriteLine(commEx); 
       client.Abort(); 
      } 
     } 
    }    

}

但是如果你client.Close更換client.Abort() ()for catch(FaultException),那麼所有東西都像魅力一樣,在第11次調用wcf後沒有鎖定 - 服務方法。

爲什麼會這樣?爲什麼在FaultException被捕獲後Abort()方法不會清理會話?

+2

你剛纔複製的粘貼在這裏呢? http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/f86c056a-4027-453a-a46c-fc223e03589b/ – oleksii 2011-05-04 17:16:33

回答

2

您是否嘗試過這種方式,我用調用WCF?

class Program 
{ 
static void Main(string[] args) 
{ 
    for(int i = 0; i < 15; i++) 
    { 
     using Service1Client client = new Service1Client() 
     { 
     try 
     { 
      client.GetData(100);     
     } 
     catch (TimeoutException timeoutEx) 
     { 
      Console.WriteLine(timeoutEx); 
      client.Abort(); 
     } 
     catch (FaultException faultEx) 
     { 
      Console.WriteLine(faultEx); 
      client.Abort(); 
     } 
     catch (CommunicationException commEx) 
     { 
      Console.WriteLine(commEx); 
      client.Abort(); 
     } 
     finally 
     { 
      client.Close(); 
     } 
     } 
    } 
}    
+0

如果它包含的,爲什麼你使用此方法的解釋這個答案會更有幫助。 – 2015-04-15 13:54:10

5

兩件事情:

  • Abort()當通信信道處於故障狀態應該被使用。使用Close()可以讓客戶端嘗試與服務進行通信,並告訴它關閉服務實例,如果願意的話,可以優雅地使用服務實例。如果通信通道處於故障狀態,則意味着不能從客戶端到服務器進行通信。在這種情況下,您應該致電Abort(),以便至少關閉客戶端。服務實例/會話將在服務器上保持活動狀態(因爲兩者之間沒有通信),並且在實例超時發生之前將保持這種狀態。如果您在故障通道上調用了Close(),則會引發更多錯誤。
  • 您的服務投擲FaultException。這並不意味着通信通道將進入故障狀態。即您仍然可以使用同一個客戶端撥打電話。因此,在你的例子中,你不應該叫Abort()

TL;博士Abort()僅關閉客戶端。服務實例/會話仍然存在。

您可以通過檢查通信信道的狀態:

ICommunicationObject comObj = ((ICommunicationObject)client); 
if(comObj.State == CommunicationState.Faulted) 
    client.Abort(); 
else 
    client.Close();