2011-04-07 24 views
1

如何在WCF双工设置中处理在客户端的回调方法中抛出的异常?WCF双工:如何处理在双工中抛出的异常回调

目前,客户端似乎没有引发故障事件(除非我对它进行了不正确的监控?),但是随后使用客户端调用Ping()失败并出现CommunicationException:“通信对象System.ServiceModel .Channels.ServiceChannel不能用于通信,因为它已被中止。“

我该如何处理这个问题并重新创建客户端等?我的第一个问题是如何找出它何时发生。其次,如何最好地处理它呢?

我的服务和回调合同:

[ServiceContract(CallbackContract = typeof(ICallback), SessionMode = SessionMode.Required)] 
public interface IService 
{ 
    [OperationContract] 
    bool Ping(); 
} 

public interface ICallback 
{ 
    [OperationContract(IsOneWay = true)] 
    void Pong(); 
} 

我的服务器上执行:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Single)] 
public class Service : IService 
{ 
    public bool Ping() 
    { 
     var remoteMachine = OperationContext.Current.GetCallbackChannel<ICallback>(); 

     remoteMachine.Pong(); 
    } 
} 

我的客户实现:

[CallbackBehavior(UseSynchronizationContext = false, ConcurrencyMode = ConcurrencyMode.Single)] 
public class Client : ICallback 
{ 
    public Client() 
    { 
     var context = new InstanceContext(this); 
     var proxy = new WcfDuplexProxy<IApplicationService>(context); 

     (proxy as ICommunicationObject).Faulted += new EventHandler(proxy_Faulted); 

     //First Ping will call the Pong callback. The exception is thrown 
     proxy.ServiceChannel.Ping(); 
     //Second Ping call fails as the client is in Aborted state 
     try 
     { 
      proxy.ServiceChannel.Ping(); 
     } 
     catch (Exception) 
     { 
      //CommunicationException here 
      throw; 
     } 
    } 
    void Pong() 
    { 
     throw new Exception(); 
    } 

    //These event handlers never get called 
    void proxy_Faulted(object sender, EventArgs e) 
    { 
     Console.WriteLine("client faulted proxy_Faulted"); 
    } 
} 

回答

1

事实证明,你不能指望该故障事件待提高。因此,要重新建立连接的最佳方式是什么时候中国平安()后续调用失败做到这一点:

我会保持代码的简洁这里:

public class Client : ICallback 
{ 
    public Client() 
    { 
     var context = new InstanceContext(this); 
     var proxy = new WcfDuplexProxy<IApplicationService>(context); 

     (proxy.ServiceChannel as ICommunicationObject).Faulted +=new EventHandler(ServiceChannel_Faulted); 

     //First Ping will call the Pong callback. The exception is thrown 
     proxy.ServiceChannel.Ping(); 
     //Second Ping call fails as the client is in Aborted state 
     try 
     { 
      proxy.ServiceChannel.Ping(); 
     } 
     catch (Exception) 
     { 
      //Re-establish the connection and try again 
      proxy.Abort(); 
      proxy = new WcfDuplexProxy<IApplicationService>(context); 
      proxy.ServiceChannel.Ping(); 
     } 
    } 
    /* 
    [...The rest of the code is the same...] 
    //*/ 
} 

显然,在我的例子代码,异常将再次抛出,但我希望这有助于让人们知道如何重新建立连接。