C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# HttpClient进行Post请求出现超时

C#使用HttpClient进行Post请求出现超时问题的解决及优化

作者:Thinbug

最近我的控制台程序发现有时候总是出现请求超时等问题,通常好几分钟最多只有3-4个请求,在使用apipost发现并发10个5分钟也没有问题,那么问题就出在我的请求端了,所以本文给大家介绍了C# 使用HttpClient进行Post请求总是出现超时问题的优化,需要的朋友可以参考下

优化结论

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

单例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请求出现超时内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文