• .NET(C#) HttpClient单例(Singleton)和每次请求new HttpClient对比


    本文主要介绍.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);
      }
    }
  • 相关阅读:
    net.sf.json.JSONObject maven下载到了但是java后台一直用不了问题
    创建springboot2.1项目运行报错
    百度地图,加载顺序异步问题,用定时器解决
    大话设计模式--(1)简单工厂模式
    H5页面单点登录跳回首页 http url参数转义
    H5页面,百度地图点击事件
    批量给数据两边加上双引号和逗号
    java基础源码 (6)--ArrayListt类
    前端 移动端H5页面 DEBUG
    H5页面,华为手机打开不加载JS的问题
  • 原文地址:https://www.cnblogs.com/fireicesion/p/16809600.html
Copyright © 2020-2023  润新知