当前位置: 代码网 > it编程>编程语言>Asp.net > C#使用HttpClient进行Post请求出现超时问题的解决及优化

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

2025年01月24日 Asp.net 我要评论
优化结论我直接上优化结论吧,就不放上老的代码了。需要从以下几个点来优化。单例httpclient问题:如果 httpclient 实例频繁创建和销毁,可能导致连接池中的资源被占满,新的请求需要等待释放

优化结论

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

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

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com