本文主要介绍.NET(C#)中,使用HttpClient执行求时,每次请求都执行new HttpClient创建一个实例和每次请求都使用同一个HttpClient(单例Singleton)分比区别。

1、每次请求创建HttpClient实例

  public HttpClient GetConnection(int timeout,string baseAddress)
        {
            HttpClient httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri(baseAddress); 
            httpClient.Timeout = System.TimeSpan.FromMilliseconds(timeout);

            return httpClient;
        }

2、每次请求使用HttpClient单例

 private static readonly Lazy<HttpClient> lazy =
        new Lazy<HttpClient>(() => new HttpClient());
        public static HttpClient Instance { get { return lazy.Value; } }
        private HttpClient getConnection(int timeout,string baseAddress)
        {
            Instance.Timeout = System.TimeSpan.FromMilliseconds(timeout);
            //client.MaxResponseContentBufferSize = 500000;
            Instance.BaseAddress = new Uri(baseAddress);
            return Instance; ;
        }

3、对比区别

HttpClient应该只被实例化一次,并在应用程序的整个生命周期中被重用。如为每个请求实例化一个HttpClient类将耗尽沉重负载下可用的套接字数量。这将导致SocketException错误。下面是正确使用HttpClient的示例。

// HttpClient是为每个应用程序实例化一次,而不是每次请求创建一个实例
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
  // 在try/catch块中调用异步网络方法来处理异常。
  try	
  {
     HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
     response.EnsureSuccessStatusCode();
     string responseBody = await response.Content.ReadAsStringAsync();
     // string responseBody = await client.GetStringAsync(uri);
     Console.WriteLine(responseBody);
  }  
  catch(HttpRequestException e)
  {
     Console.WriteLine("\nException Caught!");	
     Console.WriteLine("Message :{0} ",e.Message);
  }
}

相关文档:

system.net.http.httpclient

.net(C#)后台发送Get和Post请求的几种方法总结

ASP.net Core 2.1 httpclientFactory使用的3种方法

ASP.net Core 使用httpclient PostAsync POST Json数据

.net Core 使用httpclient通过配置Proxy(代理)执行Get和Post请求数据操作

.net(C#) Fluent HTTP (Flurl Get和Post请求)使用方法及示例代码