首页 > 编程语言 >.NET(C#) HttpClient单例(Singleton)和每次请求new HttpClient对比

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

时间:2022-10-20 13:56:02浏览次数:53  
标签:Singleton 请求 C# 实例 单例 new string 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);
  }
}

标签:Singleton,请求,C#,实例,单例,new,string,HttpClient
From: https://www.cnblogs.com/fireicesion/p/16809600.html

相关文章