ToB企服应用市场:ToB评测及商务社交产业平台

标题: 正确使用 HttpClient [打印本页]

作者: 忿忿的泥巴坨    时间: 2022-12-6 18:21
标题: 正确使用 HttpClient
正确使用 HttpClient

使用 HttpClient 注意事项

HttpClient 工厂类
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Factory
  7. {
  8.     /// <summary>
  9.     /// HttpClient工厂类
  10.     /// 注意:
  11.     /// 1. HttpClient默认最大并发连接数是2
  12.     /// 2. 本机测试HttpClient不会被限制最大并发连接数
  13.     /// </summary>
  14.     public class HttpClientFactory
  15.     {
  16.         private int _httpClientCount;
  17.         private readonly HttpClient[] _httpClientArray;
  18.         private int _index = -1;
  19.         private readonly object _lock = new object();
  20.         private static readonly HttpClientFactory _instance = new HttpClientFactory();
  21.         public static HttpClientFactory Instance
  22.         {
  23.             get
  24.             {
  25.                 return _instance;
  26.             }
  27.         }
  28.         public HttpClientFactory(int httpClientCount = 50)
  29.         {
  30.             _httpClientCount = httpClientCount;
  31.             _httpClientArray = new HttpClient[_httpClientCount];
  32.             for (int i = 0; i < _httpClientCount; i++)
  33.             {
  34.                 _httpClientArray[i] = new HttpClient();
  35.             }
  36.         }
  37.         public HttpClient Get()
  38.         {
  39.             lock (_lock)
  40.             {
  41.                 _index++;
  42.                 if (_index == _httpClientCount)
  43.                 {
  44.                     _index = 0;
  45.                 }
  46.                 return _httpClientArray[_index];
  47.             }
  48.         }
  49.     }
  50. }
复制代码
如何使用
  1. string url = "http://192.168.31.11:5028/Test/Get";
  2. HttpClient httpClient = HttpClientFactory.Instance.Get();
  3. string strResult = await (await httpClient.GetAsync(url)).Content.ReadAsStringAsync();
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4