【问题标题】:ChannelFactory: Channel Close() not closing connection (netstat shows ESTABLISHED)ChannelFactory:Channel Close() 未关闭连接(netstat 显示 ESTABLISHED)
【发布时间】:2020-05-15 21:53:15
【问题描述】:

我有一个与 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 } }
};

【问题讨论】:

    标签: c# wcf channel channelfactory servicepointmanager


    【解决方案1】:

    原来服务器返回的某些流没有正确关闭,导致客户端保持连接打开,即使在调用 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

    【讨论】:

    • 你在客户端使用过流吗?如果是这样,关闭流是否解决了问题?我在这里描述的开放连接遇到了类似的问题stackoverflow.com/questions/59929665/… 我无法控制我调用的服务,但据我所知没有涉及流。
    • 是的,我的问题是由流引起的。我已尝试回答您的问题,希望对您有所帮助。
    猜你喜欢
    • 2011-12-14
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多