0

我有一个与 WCF 服务器通信的 WPF 应用程序。

我正在使用一个 ChannelFactory 为每个呼叫创建通道:

var channel = _channelFactory.CreateChannel();
var contextChannel = channel as ICommunicationObject;
try
  {
      channel.DoSomething();
  }
  catch (Exception)
  {
      contextChannel?.Abort();
      throw;
  }
  finally
  {
      contextChannel?.Close();
  }

启动应用程序时对服务器有很多请求,在某些时候它会停止并且我得到超时。查看 netstat 我看到了一些与服务器的 ESTABLISHED 连接,

当我将 ServicePointManager.DefaultConnectionLimit 更改为 10 时,我可以处理对服务器的更多调用,但一段时间后它仍然会因超时异常而停止。

将 ServicePointManager.DefaultConnectionLimit 设置为 int.MaxValue 会处理我的所有请求,但我有大约 720 个与服务器的 ESTABLISHED 连接(服务器上的 netstat 给了我相同的结果)。

我在这里对两件事感到困惑:

  1. 看起来 WCF 不是池连接,而是为每个请求创建一个新连接
  2. 即使在我关闭频道后,连接似乎仍然建立。

我还检查了 ServicePointManager.FindServicePoint(new Uri(" https://server:3000 ")); 它确认 CurrentConnections 处于我设置为 ServicePointManager.DefaultConnectionLimit 的限制。

我已将 ServicePointManager.MaxServicePointIdleTime 减少到 500,这可以更快地关闭连接,但它仍然为我进行的每个调用创建一个连接。

在与我的服务器通信时,如何说服通道工厂重用现有通道。

这是我的绑定:

new WebHttpBinding
{
    TransferMode = TransferMode.Streamed,
    ReceiveTimeout = TimeSpan.FromMinutes(1),
    SendTimeout = TimeSpan.FromMinutes(1),
    MaxReceivedMessageSize = 2147483647,
    MaxBufferPoolSize = 2147483647,
    ReaderQuotas =
        {
            MaxDepth = 2147483647,
            MaxStringContentLength = 2147483647,
            MaxArrayLength = 2147483647,
            MaxBytesPerRead = 2147483647,
            MaxNameTableCharCount = 2147483647
        },
    Security = new WebHttpSecurity() { Mode = WebHttpSecurityMode.Transport, Transport = new HttpTransportSecurity() { ClientCredentialType = HttpClientCredentialType.None } }
};
4

1 回答 1

0

事实证明,服务器返回的某些流没有正确关闭,这导致客户端保持连接打开,即使在调用 Close() 之后也是如此。

如果调用了 Close() 并且返回给客户端的流尚未关闭,则连接将不会被重用,并且客户端将在某个时候收到 TimeoutException。

感谢张岚在 MSDN 论坛中给予提示: https ://social.msdn.microsoft.com/Forums/vstudio/en-US/a91a6d05-05ae-402e-bf7d-306289c4d0e2/wcf-with-streaming-mode -timeout-after-two-calls-when-client-and-service-are-not-on-same-machine?forum=wcf

于 2020-01-30T15:15:31.820 回答