为什么HttpClient会使套接字保持打开状态? [英] Why does HttpClient leave sockets open?

查看:105
本文介绍了为什么HttpClient会使套接字保持打开状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建,使用和处置多个HttpClient时,我注意到在TIME_WAIT状态下有一些套接字保持打开状态.

When creating, using, and disposing several HttpClients I notice that there are sockets left open in the TIME_WAIT status.

例如,运行以下命令后:

For example, after running the following:

using System.Net.Http;

namespace HttpClientTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            for (var i = 0; i < 10; i++)
            {
                using (var httpClient = new HttpClient())
                {
                   var result = httpClient.
                        GetAsync("http://stackoverflow.com/").
                        Result;
                }
            }
        }
    }
}

我用netstat注意到,套接字保持打开状态:

I notice with netstat, that sockets are left open:

TCP    10.200.60.168:2722     151.101.193.69:http    TIME_WAIT
TCP    10.200.60.168:2751     151.101.193.69:http    TIME_WAIT
TCP    10.200.60.168:2752     151.101.193.69:http    TIME_WAIT
TCP    10.200.60.168:2753     151.101.193.69:http    TIME_WAIT
TCP    10.200.60.168:2754     151.101.193.69:http    TIME_WAIT
TCP    10.200.60.168:2755     151.101.193.69:http    TIME_WAIT
TCP    10.200.60.168:2756     151.101.193.69:http    TIME_WAIT
TCP    10.200.60.168:2757     151.101.193.69:http    TIME_WAIT
TCP    10.200.60.168:2758     151.101.193.69:http    TIME_WAIT
TCP    10.200.60.168:2759     151.101.193.69:http    TIME_WAIT

这是预期的行为吗?我是否需要显式设置Connection标头值以使其关闭?

Is this expected behavior? Do I need to explicitly set the Connection header value to close to prevent this?

httpClient.
    DefaultRequestHeaders.
    Connection.
    Add("close");

推荐答案

每个HttpClient实例都将其连接池化以提高性能,但这意味着每个实例在不使用时也将池化连接留在TIME_WAIT中.

Each instance of HttpClient pools its connections for better performance, but this means that each instance also leaves the pooled connections in TIME_WAIT when they are not in use.

HttpClient实际上是线程安全的,可重入的,并且设计为可扩展使用;在程序退出之前,不应丢弃它(即使它实现了IDisposable).您应该在整个应用程序中共享一个HttpClient实例,以利用这一点.

HttpClient is actually thread-safe, reentrant, and designed for extended use; it should not be disposed of (even though it implements IDisposable) until your program exits. You should share one instance of HttpClient throughout your application to take advantage of this.

更多信息可以在此处找到.

这篇关于为什么HttpClient会使套接字保持打开状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆