C# 使用HttpClient进行Post请求总是出现超时问题的优化

最近我的控制台程序发现有时候总是出现请求超时等问题,我的程序请求不多,几分钟最多只有3-4个请求。
经过apipost测试,并发10个5分钟也没有一个超时的,那么问题就出在我的程序上了。

优化结论

我直接上优化结论吧,就不放上老的代码了。需要从以下几个点来优化。

单例HttpClient

问题:如果 HttpClient 实例频繁创建和销毁,可能导致连接池中的资源被占满,新的请求需要等待释放资源,从而造成长时间的延迟。

首先单例HttpClient,每次请求都会创建一个新的 HttpClient 实例。HttpClient 的短生命周期会导致以下问题:
1,频繁建立和销毁连接,无法复用已有的连接池。
2,增加连接开销,可能导致长时间等待(尤其在并发请求时)。
所以我们直接

private static readonly HttpClient client = new HttpClient
{
    Timeout = TimeSpan.FromSeconds(15) // 设置超时时间
};

连接池耗尽和并发

合理设置 ServicePointManager.DefaultConnectionLimit,因为就算是单例的HttpClient也会有连接数的限制。我们看看这个参数说明:

// 摘要:
//     Gets or sets the maximum number of concurrent connections allowed by a System.Net.ServicePoint
//     object.
//
// 返回结果:
//     The maximum number of concurrent connections allowed by a System.Net.ServicePoint
//     object. The default connection limit is 10 for ASP.NET hosted applications and
//     2 for all others. When an app is running as an ASP.NET host, it is not possible
//     to alter the value of this property through the config file if the autoConfig
//     property is set to true. However, you can change the value programmatically when
//     the autoConfig property is true. Set your preferred value once, when the AppDomain
//     loads.
//
// 异常:
//   T:System.ArgumentOutOfRangeException:
//     System.Net.ServicePointManager.DefaultConnectionLimit is less than or equal to
//     0.

有一句是重点
ASP的默认连接限制是10。. NET托管应用程序和其他的都是2。
我可能有时又3-4个并发,可能问题在这里,那么我直接设置100个就足够满足我的程序了。

ServicePointManager.DefaultConnectionLimit = 100; // 调高默认连接限制

并发异步

如果你的程序有很高的并发,可能会耗尽你的CPU,那么需要使用异步。

HttpResponseMessage response = await client.PostAsync(url, content);

最终优化后

我最终的代码状态如下:

public async Task<string> PostFormResult(string url, string parm)
{
    Log("PostFormResult 开始请求: " + url + ", parm: " + parm);
    try
    {
        byte[] buf = Encoding.UTF8.GetBytes(parm);
        using (HttpContent content = new ByteArrayContent(buf))
        {
        	//这里我是表单,可以换成json
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
			//content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
			//添加Token	
		    //client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

            HttpResponseMessage res = await client.PostAsync(url, content);

            if (res.IsSuccessStatusCode)
            {
                string json = await res.Content.ReadAsStringAsync();
                Log("PostFormResult请求成功: " + json);
                return json;
            }
            else
            {
                Warning("PostFormResult请求失败: " + res.StatusCode);
            }
        }

    }
    catch (HttpRequestException ex)
	{
	    Warning("请求Post出现错误: " + ex.Message);
	}
	catch (Exception ex)
	{
	    Warning($"请求Post出现错误: {ex.Message}");
	}
    return string.Empty;
}

我的请求会同时出现了4个。所以超过了并发所以产生了问题,修改后就没有问题了。

### 如何使用 C# 的 `HttpClient` 发送 POST 请求 要通过 C# 使用 `HttpClient` 类发送 POST 请求,通常需要构建 HTTP 内容并指定目标 URI。下面是一个完整的例子来展示如何实现这一点: ```csharp using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; public class PostExample { public static async Task SendPostRequest() { using (var httpClient = new HttpClient()) { string url = "https://example.com/api/resource"; // 创建 JSON 或其他格式的内容字符串 var contentString = "{\"key\":\"value\"}"; // 将内容转换成 HttpContent 对象 StringContent httpContent = new StringContent( contentString, Encoding.UTF8, "application/json" ); HttpResponseMessage response = await httpClient.PostAsync(url, httpContent); if (response.IsSuccessStatusCode) { Console.WriteLine("POST request succeeded."); // 可选:读取响应体作为字符串 string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Response body: {responseBody}"); } else { Console.WriteLine($"Error occurred while sending POST request. Status code: {response.StatusCode}"); } } } } ``` 此代码片段展示了如何创建一个简单的 POST 请求[^1]。这里定义了一个异步方法 `SendPostRequest()` 来执行实际的操作。注意,在这个过程中还设置了请求头中的 Content-Type 为 application/json。 对于更复杂的场景,可能还需要处理认证、超时设置等问题。如果应用程序频繁地向同一服务器发出多个请求,则建议重用同一个 `HttpClient` 实例而不是每次都新建一个新对象[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Thinbug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值