随笔 - 165, 文章 - 0, 评论 - 18, 阅读 - 22万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
本文主要介绍.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);
  }
}
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示