正确使用 HttpClient
使用 HttpClient 注意事项
- HttpClient默认最大并发连接数是2
- 本机测试(被请求的WebApi部署在本机)HttpClient不会被限制最大并发连接数
- 使用HttpClient要写个工厂类,因为HttpClient不能频繁创建
- HttpClient类提供的方法是线程安全的
HttpClient 工厂类
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Factory
- {
- /// <summary>
- /// HttpClient工厂类
- /// 注意:
- /// 1. HttpClient默认最大并发连接数是2
- /// 2. 本机测试HttpClient不会被限制最大并发连接数
- /// </summary>
- public class HttpClientFactory
- {
- private int _httpClientCount;
- private readonly HttpClient[] _httpClientArray;
- private int _index = -1;
- private readonly object _lock = new object();
- private static readonly HttpClientFactory _instance = new HttpClientFactory();
- public static HttpClientFactory Instance
- {
- get
- {
- return _instance;
- }
- }
- public HttpClientFactory(int httpClientCount = 50)
- {
- _httpClientCount = httpClientCount;
- _httpClientArray = new HttpClient[_httpClientCount];
- for (int i = 0; i < _httpClientCount; i++)
- {
- _httpClientArray[i] = new HttpClient();
- }
- }
- public HttpClient Get()
- {
- lock (_lock)
- {
- _index++;
- if (_index == _httpClientCount)
- {
- _index = 0;
- }
- return _httpClientArray[_index];
- }
- }
- }
- }
复制代码 如何使用
- string url = "http://192.168.31.11:5028/Test/Get";
- HttpClient httpClient = HttpClientFactory.Instance.Get();
- string strResult = await (await httpClient.GetAsync(url)).Content.ReadAsStringAsync();
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |