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

为了测试此设置,我启动了客户端应用程序和 Web 服务(都在我的本地计算机上),一切正常。我尝试通过终止网络服务并重新启动它来模拟糟糕的互联网连接。一旦我终止该服务,我就开始收到 CommunicationObjectFaultedExceptions——这是预期的。但在我重新启动服务后,我继续收到这些异常。

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

谢谢!

克莱

有帮助吗?

解决方案

客户端服务代理一旦出现故障就无法重复使用。您必须处理掉旧的并重新创建一个新的。

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

例如:

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;
}

有一篇关于此的博客文章 这里

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top