正确使用 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];
}
}
}
}
标签:index,正确,HttpClientFactory,System,private,使用,httpClientCount,HttpClient
From: https://www.cnblogs.com/s0611163/p/16955790.html