从WCF中的CommunicationObjectFaultedException中恢复

Kla*_*lay 14 wcf exception channel

我有一个客户端应用程序,每10秒尝试通过WCF Web服务发送一条消息.这个客户端应用程序将在船上的计算机上,我们知道它将具有不稳定的互联网连接.我希望应用程序尝试通过服务发送数据,如果不能,则排队消息,直到它可以通过服务发送它们.

为了测试这个设置,我启动了客户端应用程序和Web服务(都在我的本地机器上),一切正常.我试图通过杀死Web服务并重新启动它来模拟糟糕的Internet连接.一旦我终止服务,我就开始获得CommunicationObjectFaultedExceptions - 这是预期的.但是在我重新启动服务之后,我继续得到这些例外.

我很确定我对Web服务范例有些不了解,但我不知道那是什么.任何人都可以提供有关此设置是否可行的建议,如果可行,如何解决此问题(即重新建立与Web服务的通信渠道)?

谢谢!

克莱 -

Sim*_*ens 34

客户端服务代理一旦出现故障就无法重用.您必须丢弃旧的并重新创建一个旧的.

您还必须确保正确关闭客户端服务代理.WCF服务代理可能会在关闭时抛出异常,如果发生这种情况,则连接不会关闭,因此您必须中止.使用"try {Close}/catch {Abort}"模式.还要记住dispose方法调用close(因此可以从dispose中抛出异常),所以你不能只使用类似普通的一次性类.

例如:

try
{
    if (yourServiceProxy != null)
    {
        if (yourServiceProxy.State != CommunicationState.Faulted)
        {
            yourServiceProxy.Close();
        }
        else
        {
            yourServiceProxy.Abort();
        }
    }
}
catch (CommunicationException)
{
    // Communication exceptions are normal when
    // closing the connection.
    yourServiceProxy.Abort();
}
catch (TimeoutException)
{
    // Timeout exceptions are normal when closing
    // the connection.
    yourServiceProxy.Abort();
}
catch (Exception)
{
    // Any other exception and you should 
    // abort the connection and rethrow to 
    // allow the exception to bubble upwards.
    yourServiceProxy.Abort();
    throw;
}
finally
{
    // This is just to stop you from trying to 
    // close it again (with the null check at the start).
    // This may not be necessary depending on
    // your architecture.
    yourServiceProxy = null;
}
Run Code Online (Sandbox Code Playgroud)

有关于这一个博客文章在这里