15

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

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

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

谢谢!

克莱

4

1 回答 1

39

客户端服务代理一旦出现故障就不能被重用。您必须处理旧的并重新创建一个新的。

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

例如:

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

一篇关于此的博客文章,但现在似乎已离线。Wayback Machine 上有存档版本。

于 2009-08-06T20:51:51.367 回答